[英]Workbook_Open Subscript out of Range
I am having issues with writing a macro in VBA when it is being initiated with the opening of my workbook. 我在打开工作簿时开始在VBA中编写宏时遇到问题。 The error reads 'Error 9 - Subscript out of range'.
错误显示为“错误9-下标超出范围”。
The Macro should look to see if there is a 'control' sheet in the current workbook, if not then it will open another workbook and copy the control sheet over - closing that workbook as it does so. 宏应查看当前工作簿中是否有一个“控制”表,如果没有,则它将打开另一个工作簿并复制该控制表,从而关闭该工作簿。
This is a strange one because it actually works if I attach it to a button, but doesn't work when I try and initiate the Macro when you open the file. 这很奇怪,因为如果我将它附加到按钮上,它实际上可以工作,但是当我尝试在打开文件时启动宏时却无法工作。
Here is my code; 这是我的代码;
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
As you haven't qualified which workbook contains worksheet "Control", you're implicitly referring to the activeworkbook, and you've already proven that worksheet "Control" doesn't exist... Qualify your worksheet reference (oh, and always declare your variables!) 由于您尚未限定哪个工作簿包含工作表“控件”,因此您隐式地引用了活动工作簿,并且您已经证明工作表“控件”不存在...限定您的工作表引用(哦,总是声明您的变量!)
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.