对象'_global'的方法'工作表'失败

时间:2017-06-26 12:40:36

标签: vba excel-vba excel

我现在已经完成了这个错误,并且在经过大量搜索后没有找到解决方案。该错误仅发生在代码的每次执行时。我将发布处理Excel的代码部分,因为这显然是问题所在。所有变量都已定义,但我将包括我对重要变量的定义。

Dim msEX As Excel.Application
Dim exBook As Excel.Workbook

Set msEX = New Excel.Application
msEX.Visible = True

Set exBook = msEX.Workbooks.Open(CurrentProject.Path & "\Bookings.xlsx")
exBook.Activate

If SheetExists("Template (2)", exBook) = True Then
    msEX.DisplayAlerts = False
    exBook.Worksheets("Template (2)").Delete
    msEX.DisplayAlerts = True
End If
exBook.Worksheets("Template").Copy After:=Worksheets("Template")

If SheetExists(sheetName, exBook) Then
    On Error Resume Next
    exBook.Worksheets(sheetName).Name = sheetName & " (old)"
    exBook.Worksheets("Template (2)").Name = sheetName
    Do While Err <> 0
        Err.Clear
        newSheetName = InputBox("Please enter a new name for the sheet", "Worksheet name is taken")
        If newSheetName = "" Then
            exBook.Close True
            MsgBox ("Invalid Name, sheet not created")
            Exit Sub
        End If
        exBook.Worksheets("Template (2)").Name = newSheetName
    Loop
    On Error GoTo 0
Else
    exBook.Worksheets("Template (2)").Name = sheetName
End If

exBook.Worksheets(sheetName).Range("A1").Value = r!Course
exBook.Worksheets(sheetName).Range("A2").Value = r![Start Date]
exBook.Worksheets(sheetName).Range("B3").Value = venName & " " & r![Start Time]

For i = 0 To i = UBound(learnerNames) - LBound(learnerNames) + 1
    exBook.Worksheets(sheetName).Range("C" & i + 6).Value = learnerNames(i)
Next i

For i = 0 To i = UBound(learnerPhones) - LBound(learnerPhones) + 1
    exBook.Worksheets(sheetName).Range("D" & i + 6).Value = learnerPhones(i)
Next i

For i = 0 To i = UBound(learnerEmails) - LBound(learnerEmails) + 1
    exBook.Worksheets(sheetName).Range("E" & i + 6).Value = learnerEmails(i)
Next i

exBook.Save

End If

我们非常感谢任何建议。

1 个答案:

答案 0 :(得分:0)

exBook.Worksheets("Template").Copy After:=Worksheets("Template")

只有以上行有一个不合格的Worksheets电话。将其改为

exBook.Worksheets("Template").Copy After:=exBook.Worksheets("Template")
'                                         ^^^^^^^