繁体   English   中英

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

[英]VBA Error: 'Range' of object '_Global' Failed

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

我知道错误是由于错误的单元格引用引起的,但我没有尝试解决这个问题,因此代码每次执行时都能正常工作。 我感谢任何人可以提供的任何见解。 谢谢你。

    '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

必须符合您的工作表。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM