我有一個簡單的代碼位,如下圖所示標越界:運行時錯誤9複製SEET時,一個新的wrokbook
Private Sub btn_conact_Click()
Dim projectref As String
Dim savelocation As String
Dim projectSearchRange As Range
Dim LastRow As Integer
'set search value (porject key - unique)
projectref = cmb_Project.Value
Application.ScreenUpdating = False
'find the project reference in the tracking spreadsheet
Sheets("Project Tracking").Activate
Set projectSearchRange = Range("A:A").Find(projectref, , xlValues, xlWhole)
LastRow = projectSearchRange.Row
'file directory to save the new workbook in
savelocation = Cells(LastRow, 5).Value
'template for the contact list
Sheets("Contact List").Activate
Cells(7, 3).Value = projectref
'create new workbook
Set newWorkbook = Workbooks.Add
With newWorkbook
.Title = "Contact List for Project" & projectref
.SaveAs Filename:=savelocation & "/" & projectref & "Contact_List.xlsx"
End With
'Windows("Project tracker spreadsheet VBA").Activate
Sheets("Contact List").Copy Before:=Workbooks(projectref & "Contact_List.xlsx").Sheets("Sheet1") 'runtime error 9: subscript out of range
Windows(projectref & " Contact_List.xlsx").Activate
Application.ScreenUpdating = True
End Sub
可以看出,我得到的運行時錯誤第四最後一行代碼,這是一個非常重要的行...
我的問題是,任何人都可以看到我可能犯了一個錯誤,會導致這個錯誤嗎?已成功創建新工作簿並將其保存在指定位置,但只是在嘗試從舊工作簿(Project tracker spreadsheet VBA)複製所需工作表到此代碼創建的新工作簿時發生。
爲什麼註釋掉這一行'的Windows( 「項目跟蹤電子表格VBA」)Activate'?刪除代碼中此行之前的單引號。 – sn152
「舊」工作簿的名稱是什麼?如果是「項目跟蹤器電子表格VBA.xlsm」,那麼你應該使用Workbooks(「項目跟蹤器電子表格VBA.xlsm」)表格(「聯繫人列表」)。複製之前:= Workbooks(projectref&「Contact_List.xlsx 「).Sheets(」Sheet1「)' – YowE3K