我想打开并在两个工作簿上工作,但是我仍然遇到错误'运行时错误'9' 我在哪里犯错? 我编写了这段代码,并且在设置Wbook1和Wbook2时遇到了问题
Sub List()
Dim Wbook1 As Workbook, Wbook2 As Workbook
Dim strWbook1 As String, strWbook2 As String
strWbook1 = "C:\CW3_test.xls"
strWbook2 = "C:\CW3 Document register.xls"
Set Wbook1 = Workbooks(strWbook1)
Set Wbook2 = Workbooks.Open(strWbook2)
Dim ark1 As Worksheet, ark2 As Worksheet
Set ark1 = Wbook1.Worksheets("Arkusz1")
Set ark2 = Wbook1.Worksheets("MAN")
Dim NextRow As Long
Dim LastRow As Long, lastRow2 As Long
Dim StartTime As Double
StartTime = Timer
Wbook1.ark2.Select
Wbook1.ark2.Cells.Select
Selection.ClearContents
LastRow = Wbook1.ark1.Cells(Rows.Count, 2).End(xlUp).Row
Wbook2.Active
ActiveWorkbook.Close savechanges:=False
MsgBox "Time:" & Format((Timer - StartTime) / 86400, "hh:mm:ss")
End Sub```
答案 0 :(得分:2)
Wbook1.ark2.Select
ark2
是一个工作表变量-它不是Wbook1的属性或方法。
ark2.Select
可以正常工作,但是在VBA中使用Excel时通常不需要激活/选择任何内容。
Sub List()
Dim Wbook1 As Workbook, Wbook2 As Workbook
Dim strWbook1 As String, strWbook2 As String
strWbook1 = "C:\CW3_test.xls"
strWbook2 = "C:\CW3 Document register.xls"
Set Wbook1 = Workbooks(strWbook1)
Set Wbook2 = Workbooks.Open(strWbook2)
Dim ark1 As Worksheet, ark2 As Worksheet
Set ark1 = Wbook1.Worksheets("Arkusz1")
Set ark2 = Wbook1.Worksheets("MAN")
Dim NextRow As Long
Dim LastRow As Long, lastRow2 As Long
Dim StartTime As Double
StartTime = Timer
ark2.Cells.ClearContents 'no need to activate/select
LastRow = ark1.Cells(ark1.Rows.Count, 2).End(xlUp).Row
Wbook2.Close savechanges:=False 'no need to activate/select
MsgBox "Time:" & Format((Timer - StartTime) / 86400, "hh:mm:ss")
End Sub