微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

VBA错误:对象“ _Global”的“范围”失败

如何解决VBA错误:对象“ _Global”的“范围”失败

我正在使用MS Access和MS Excel自动执行重复过程,其中删除旧的.csv文件,在该位置创建一个新的.csv文件,用数据填充一组单元格,保存并关闭文件。以下代码在每次执行奇数次时均按预期工作。每到偶一次,我在第29行(用***标记)都会收到“ _Global”对象失败的“'Range'”。当我收到错误消息时,我结束了进程并关闭了它不保存而创建的Excel窗口。然后,当我再次执行代码时,它就会起作用。

我知道该错误是由于错误的单元格引用引起的,但是我尝试过的任何方法都不能解决该问题,因此每次执行该代码时,代码都可以工作。我感谢任何人都可以提供的见解。谢谢。

    'Creating Excel Application and workbook instance
    Dim x1 As New Excel.Application
    Dim xWB As Excel.Workbook
    
    'Delete PrevIoUs version of file to avoid overwrite errors
    If Dir("Z:\ETI\01 ETI Engine\automated\ETI Hootsuite FaceBook Feed.csv") <> "" Then
        Kill ("Z:\ETI\01 ETI Engine\automated\ETI Hootsuite FaceBook Feed.csv")
    End If
    
    'Open new Workbook and save as CSV
    Excel.Application.displayAlerts = False
    Set x1 = New Excel.Application
    Set xWB = x1.Workbooks.Add
    x1.Visible = True
    xWB.SaveAs "Z:\ETI\01 ETI Engine\automated\ETI Hootsuite FaceBook Feed.csv",FileFormat:=xlCSV
       
    'Assign values to each post,after checking that they are not scheduled in the past.
    Dim url As String
    url = "https://web-ded.uta.edu/wconnect/CourseStatus.awp1?&course=" & Me.txtCourseCode
    
    Dim i As Integer
    For i = 1 To 4
        'Create and assign a generated date for the post
        Dim rndDate As Date
        rndDate = SocialMedia.randDateFB(Me.txtBegDate,i)
        'if the random date is after Now,then create the post.
        If rndDate > Now() Then
            With xWB.Worksheets("ETI Hootsuite FaceBook Feed")
                ***.Range("A" & i).Value = rndDate
                .Range("B" & i).Value = SocialMedia.fbPost(Me.txtCatCode,SocialMedia.courseLocation(Me.txtCity,Me.txtState,Me.chkSimulcast),SocialMedia.courseDates(Me.txtBegDate,Me.txtEndDate))
                .Range("C" & i).Value = url
            End With
        Else
        End If
    Next i
    
    'Removes empty rows and removes duplicate posts to meet Hootsuite standards
    Range("A1","C100").RemoveDuplicates Columns:=Array(2),Header:=xlNo
    Range("A1","C100").RemoveDuplicates Columns:=Array(1),Header:=xlNo
    
    
    'The following code helped close a program loop,so that it doesn't need to be manually reset every time the code is run.
    xWB.Save
    xWB.Close
    x1.Quit
    
    Set x1 = nothing
    Set xWB = nothing
    
    Me.chkFacebookLinkedInPostsSent.Value = True

解决方法

每个Excel方法/属性/对象都必须具有自己的Excel对象。否则,它将创建保留有效的全局引用,并使您的代码第二次停止工作。

这些都留在您的代码中:

Excel.Application.DisplayAlerts = False

更改为

x1.DisplayAlerts = False

Range("A1","C100").RemoveDuplicates Columns:=Array(2),Header:=xlNo
Range("A1","C100").RemoveDuplicates Columns:=Array(1),Header:=xlNo

必须符合您的工作表。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。