我创建了一个工作簿,该工作簿仅在使用以下代码运行时显示用户窗体
Private Sub Workbook_Open()
Application.Visible = False
UserForm1.Show
End Sub
初始化用户窗体时,它将打开另一个工作簿(WHITEBOOK.xls)。在将数据输入到表单中并用户单击“提交”按钮后,数据将插入到已打开的工作簿中(我省略了该代码,但它可以工作)
Private Sub UserForm_Initialize()
Set wb = Workbooks.Open("S:\!Data Tracking\WHITEBOOK.xls")
wb.Sheets("Jobs with Correct Template").Activate
If IsEmpty(wb.Worksheets("Jobs with Correct Template").Range("A3").Value) = True Then
Set SheetNameCellRange = wb.Worksheets("Jobs with Correct Template").Range("A2")
Else
wb.Worksheets("Jobs with Correct Template").Activate
Set SheetNameCellRange = wb.Worksheets("Jobs with Correct Template").Range("A2", Range("A2").End(xlDown))
End If
End Sub
当用户关闭UserForm时,我使用此代码关闭表单,并关闭UserForm的工作簿。
Private Sub UserForm_Terminate()
Unload Me
For Each wb In Application.Workbooks
If (StrComp(wb.Name, "Whitebook Data Entry (Final).xlsm", vbTextCompare) = 0) Then
wb.Close
End If
Next
End Sub
我遇到的问题是,如果WHITEBOOK.xls工作簿已经打开,则无法打开UserForm。我收到运行时错误“ 9”:下标超出范围,它在UserForm_Initialize()子程序的这一行失败。
wb.Sheets("Jobs with Correct Template").Activate
我尝试在打开WHITEBOOK工作簿时添加条件,以检查它是否已经打开,如果已经打开,则使其处于活动状态,但是我一直遇到相同的问题。
我用来测试工作簿是否打开的代码是
Private Sub UserForm_Initialize()
Dim wkb As Workbook
On Error Resume Next
Set wkb = Application.Workbooks("S:\!Data Tracking\WHITEBOOK.xls")
If wkb Is Nothing Then
Set wb = Workbooks.Open("S:\!Data Tracking\WHITEBOOK.xls")
Else
wb.Sheets("Jobs with Correct Template").Activate
End If