上週我已經發布了一個密切相關的問題VBScript to add code to Excel workbook由一位程序員解決了。但我遇到了下一個問題:VBScript通過Excel文件循環並更改宏
用下面的代碼,我嘗試循環訪問Excel文件的文件夾,然後逐個打開它們,並在DieseArbeitsmappe
中更改宏。這適用於第一個文件,但第二個文件以此錯誤消息結束。 Error message
Set objFSO = CreateObject("Scripting.FileSystemObject")
sFolder = "P:\Administration\Reports\operativ\Tagesbericht\templates\START07\TestTabsiNeu\"
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
objExcel.DisplayAlerts = False
For Each objFile In objFSO.GetFolder(sFolder).Files
Set objWorkbook = objExcel.Workbooks.Open(sFolder & objFile.Name)
Set component = objworkbook.VBProject.VBComponents("DieseArbeitsmappe")
strCode = _
"Sub WorkBook_Open() 'just for testing" & vbCr & _
" Application.Run (""'CommonMacro.xlsm'!Workbook_Open"")" & vbCr & _
"End Sub"
component.CodeModule.AddFromString strCode
objWorkbook.SaveAs "P:\Administration\Reports\operativ\Tagesbericht\templates\START07\TestTabsiNeu\" & objFile.Name
objExcel.Quit
Set objWorkbook = Nothing
Set component = Nothing
Next
Set objFSO = Nothing
Set objExcel = Nothing
線10 Set component = objworkbook.VBProject.VBComponents("DieseArbeitsmappe")
我即將面臨的另一個問題是,有時VBComponent
被稱爲ThisWorkbook
。所以我將不得不根據第10行拋出的錯誤碼引入if-else
。或者有更好的解決方案嗎?
在此先感謝您的幫助。
更換
你可以做到這一點,但寫一個專門的函數返回你適當的組件。把錯誤處理放在這個函數裏面(如果錯誤得到「ThisWorkbook」等等,嘗試獲得VBComponents(「DieseArbeitsmappe」)) –
備註:替換'objWorkbook.SaveAs「P:\ Administration \ Reports \ operativ \ Tagesbericht \ templates \ START07 \ TestTabsiNeu \''帶'objWorkbook.SaveAs sFolder' –