在打开工作簿时启动宏时,我在用VBA编写宏时遇到问题。错误显示为“错误9-下标超出范围”。
该宏应查看当前工作簿中是否有一个“控制”表,如果没有,则它将打开另一个工作簿并复制该控制表,从而关闭该工作簿。
这很奇怪,因为如果我将它附加到按钮上,它实际上可以工作,但是当我尝试在打开文件时启动宏时却无法工作。
这是我的代码;
Private Sub Workbook_Open()
' CreateEUC Macro
ScreenUpdating = False
For i = 1 To Worksheets.Count
If Worksheets(i).Name = "Control" Then
exists = True
MsgBox ("There is already an EUC slide in this workbook")
End If
Next i
If Not exists Then
' Open Location
Workbooks.Open "T:\Pricing\EUC Inventory\EUC Control Sheet v0.4.xlsx"
' Copy/Paste EUC
Sheets("Control").Copy After:=ThisWorkbook.Sheets(1)
' Close EUC Workbook
Workbooks("EUC Control Sheet v0.4.xlsx").Close savechanges:=False
' Move sheet at front of workbook
Sheets("Control").Move Before:=Sheets(1)
Range("A1:H1").Select
End If
ScreenUpdating = True
End Sub
答案 0 :(得分:0)
由于您尚未限定哪个工作簿包含工作表“控件”,因此您隐式引用了活动工作簿,并且您已经证明工作表“控件”不存在...限定您的工作表引用(哦,并始终声明您的变量!)
Private Sub Workbook_Open()
Dim i As Integer
Dim exists As Boolean
Application.ScreenUpdating = False
For i = 1 To Worksheets.Count
If Worksheets(i).Name = "Control" Then
exists = True
MsgBox ("There is already an EUC slide in this workbook")
End If
Next i
If Not exists Then
With Workbooks.Open("T:\Pricing\EUC Inventory\EUC Control Sheet v0.4.xlsx") ' Open Location
.Sheets("Control").Copy After:=ThisWorkbook.Sheets(1) ' Copy/Paste EUC
.Close savechanges:=False ' Close EUC Workbook
End With
Sheets("Control").Move Before:=Sheets(1) ' Move sheet to front of workbook
Range("A1:H1").Select
End If
Application.ScreenUpdating = True
End Sub