我正在尝试编写一个子程序,它将当前工作簿(带有子程序的工作簿)中的工作表列出到一个名为 ListAllSheets 的工作簿中,但在如何访问 ListAllSheets 以将名称写入其中时变得有点卡住了,这就是我到目前为止。
Sub ListAllSheets()
'Create variables
Dim outputFile As String
Dim mainworkBook As Workbook
Set mainworkBook = ActiveWorkbook
'Assign the file to outputFile
outputFile = "D:\QA\ListAllSheets.xlsx"
On Error Resume Next
Workbooks("ListAllSheets.xlsx").Close SaveChanges:=False
On Error GoTo 0
'Delete old file if it exists
If Len(Dir$(outputFile)) > 0 Then
Kill outputFile
End If
'Create new file
Workbooks.Add.SaveAs Filename:=outputFile
'List all the sheet in current file into the outputFile
For i = 1 To mainworkBook.Sheets.Count
Sheets("Sheet1").Range(“A” & i) = mainworkBook.Sheets(i).Name
Next i
End Sub
当我运行它时,我要么得到一个错误,要么它列出了错误工作簿中的工作表。
更新代码:
Sub ListAllSheets()
'Create variables
Dim outputFile As String
Dim mainworkBook As Workbook
Dim newworkBook As Workbook
'Assign the file to outputFile
outputFile = "D:\QA\ListAllSheets.xlsx"
Set newworkBook = Workbooks(outputFile)
Set mainworkBook = ActiveWorkbook
On Error Resume Next
Workbooks("ListAllSheets.xlsx").Close SaveChanges:=False
On Error GoTo 0
'Delete old file if it exists
If Len(Dir$(outputFile)) > 0 Then
Kill outputFile
End If
'Create new file
Workbooks.Add.SaveAs Filename:=outputFile
'List all the sheet in current file into the outputFile
For i = 1 To mainworkBook.Sheets.Count
newworkBook.Sheets("Sheet1").Range(“A” & i) = mainworkBook.Sheets(i).Name
Next i
End Sub
在它说的地方
Sheets("Sheet1").Range(“A” & i) = mainworkBook.Sheets(i).Name
,考虑指定要写入哪个工作簿,方法是将新工作簿放入变量(例如 newworkBook)并调用newworkBook.Sheets("Sheet1").Range(“A” & i) = mainworkBook.Sheets(i).Name
.这将指定要输出到哪个工作簿,这似乎是您的问题。