我有一個宏從特定文件夾打開電子表格,並將輸出保存到另一個工作簿中名爲Sheet1的工作表中。如果文件名被稱爲「MyFile.xls」,該宏可以工作,但我希望它能夠在任何文件名上運行,但它必須具有「Book2」工作表。VBA打開任何工作簿
這裏是我的代碼:
Dim source As Workbook
Dim output As Workbook
Dim sourceSheet as WorkSheet
Dim outputSheet as WorkSheet
Dim file As String
file = "C:\Spreadsheets\MyFile.xls" 'I would like it to handle any files from any location'
Set output = ThisWorkBook
output.Activate
If Len(Dir$(file)) > 0 Then
Set source = workbooks.Open(file)
Set sourceSheet = source.Worksheets("Book2") 'Must only run if the sheet is called Book2'
Set outputSheet = output.Worksheets("Sheet1") 'Saves sheets into a new sheet called Sheet1'
End Sub
是否表示如果沒有名爲「Book2」的表,它應該不運行? –
是的,如果不應該運行,如果沒有名爲Book2的表,但它可以打開任何Excel文件,而不僅僅是MyFile.xls – user2273278
我發現一個錯誤。我測試了代碼並修改了我的帖子。請刷新頁面以查看最新的答案。 –