簡體   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