-2
我在打開多個Excel文件並在每個文件上運行相同的宏(包含在每個文件中)。如何打開多個Excel文件並在每個文件上執行包含的宏?
例如,我想自動打開h:\ dbs中的每個文件,並在每個文件中執行CmdUpdate_Click
宏。
我該怎麼辦?
我在打開多個Excel文件並在每個文件上運行相同的宏(包含在每個文件中)。如何打開多個Excel文件並在每個文件上執行包含的宏?
例如,我想自動打開h:\ dbs中的每個文件,並在每個文件中執行CmdUpdate_Click
宏。
我該怎麼辦?
嘗試類似這樣的東西。我希望你可以研究如何打開Visual Basic編輯器並找出粘貼的位置。
'Declare variables
Dim FolderObj, FSO, FileObj As Object
Dim FolderDialog As FileDialog
'Create and run dialog box object
Set FolderDialog = Application.FileDialog(msoFileDialogFolderPicker)
With FolderDialog
.ButtonName = "Select"
.AllowMultiSelect = False
.InitialFileName = "B:\BIM Projects\"
.InitialView = msoFileDialogViewDetails
'Check if user canceled dialog box
'Exit if yes
If .Show = -1 Then
MsgBox "No Folder Selected"
Exit Sub
End If
End With
'Check if user canceled dialog box
'Exit if yes
'Create a File System Object to be the folder that was selected
Set FSO = CreateObject("scripting.filesystemobject")
Set FolderObj = FSO.getfolder(FolderLocation)
'For each obj in the selected folder
For Each FileObj In FolderObj.Files
'Test if the file extension contains "xl" and make sure it's an Excel file before opening
If InStr(1, Right(FileObj.Name, Len(FileObj.Name) - InStr(1, FileObj.Name, ".")), "xl") = 1 Then
'Prevent the workbook from displaying
ActiveWindow.Visible = False
'Open the Workbook
Workbooks.Open (FolderObj & "\" & FileObj.Name)
'Run the Macro
Application.Run "'" & FolderObj & "\" & FileObj.Name & "'!CmdUpdate_Click"
'Save the Workbook
Workbooks(FileObj.Name).Save
'Close the Workbook
Workbooks(FileObj.Name.Close
End If
'Turn this back on
ActiveWindow.Visible = True
Next
我會提醒你,這是基於一些代碼,我寫了字,所以也不能保證它會工作,我沒有時間來測試它。但是,如果沒有,它會給你一個很好的開始。
編輯地址:您可能需要
首先,瀏覽一下VBA的教程,就像這樣:http://www.excel-easy.com/vba.html。您將需要workbooks.Open()方法:https://msdn.microsoft.com/en-us/library/office/ff194819.aspx。一旦你給了它一個鏡頭,並卡住,發佈你的問題在這裏,我們將很樂意爲您提供幫助! – CodeJockey