我已经搜索了这个问题,并且从其他线程中搜索它似乎与受保护的工作表,隐藏的工作表或不正确的文件名有关,但似乎对我来说不是问题。
我只有一个电子表格文件存在此问题。该工作簿只有一个工作表,我正在尝试添加一个名为“ Sheet4”的工作表。
我已经使用其他多个电子表格进行了测试,并且可以正常工作。
代码如下:
Sub TestAddingSheet()
Dim wb1 As Workbook, wb2 As Workbook
Dim sh1 As Worksheet, sh2 As Worksheet
Dim WbName As String
WbName = ActiveWorkbook.Name
Set wb1 = Workbooks(WbName)
Set wb2 = Workbooks.Open("C:\test\test.xlsx")
Set sh1 = wb1.Sheets.Add(After:=Sheets(Sheets.Count))
sh1.Name = "Sheet4"
Set sh2 = wb1.Worksheets(1)
End Sub
我可以使用它的方法是在添加新表之前激活wb1,如下所示:
Sub TestAddingSheet()
Dim wb1 As Workbook, wb2 As Workbook
Dim sh1 As Worksheet, sh2 As Worksheet
Dim WbName As String
WbName = ActiveWorkbook.Name
Set wb1 = Workbooks(WbName)
Set wb2 = Workbooks.Open("C:\test\test.xlsx")
wb1.Activate
Set sh1 = wb1.Sheets.Add(After:=Sheets(Sheets.Count))
sh1.Name = "Sheet4"
Set sh2 = wb1.Worksheets(1)
End Sub
为什么原始代码不适用于所有电子表格?