我在perforce中有一个shered文件夹,其中有很多子文件夹,其中有超过1000个excel文件,我正在为我使用的特定宏运行以下代码(这改变了wb中的内容)。 我还需要在这些文件中应用该宏。我的意思是我希望在文件上运行代码后可以在每个excel文件中使用该宏,以便在其他计算机中重复使用吗?
Sub ProcessFiles()
Dim objFolder As Object
Dim objFile As Object
Dim objFSO As Object
Dim MyPath As String
Dim myExtension As String
Dim FldrPicker As FileDialog
Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)
With FldrPicker
.Title = "Select A Target Folder"
.AllowMultiSelect = False
If .Show <> -1 Then Exit Sub ' < can use Exit Sub instead of GoTo
MyPath = .SelectedItems(1)
End With
Application.DisplayAlerts = False ' <-- add this line
Application.ScreenUpdating = False
Set objFSO = CreateObject("Scripting.FileSystemObject")
Call GetAllFiles(MyPath, objFSO)
Call GetAllFolders(MyPath, objFSO)
' restore default settings
Application.ScreenUpdating = True
Application.DisplayAlerts = True
MsgBox "Complete."
End Sub
Sub GetAllFiles(ByVal strPath As String, ByRef objFSO As Object)
Dim objFolder As Object
Dim objFile As Object
Set objFolder = objFSO.GetFolder(strPath)
For Each objFile In objFolder.Files
DoWork objFile.Path
Next objFile
End Sub
Sub GetAllFolders(ByVal strFolder As String, ByRef objFSO As Object)
Dim objFolder As Object
Dim objSubFolder As Object
Set objFolder = objFSO.GetFolder(strFolder)
For Each objSubFolder In objFolder.subfolders
Call GetAllFiles(objSubFolder.Path, objFSO)
Call GetAllFolders(objSubFolder.Path, objFSO)
Next objSubFolder
End Sub
Sub DoWork(strFile As String)
Dim wb As Workbook
If Right(strFile, 4) = ".xls" Then
Set wb = Workbooks.Open(Filename:=strFile)
With wb
'Do your work here
......
.Close True
End With
End If
End Sub
答案 0 :(得分:1)
如上面的评论中所述,您可以将代码放在.bas模块文件中,然后通过VBE将其导入每个Excel文件。
workbook.VBProject.VBComponents.Import ("mymodule.bas")
请注意,您的Excel电子表格不受密码保护!
答案 1 :(得分:1)
您可能还想查看使用AddIn,然后您可以加载AddIn以使代码可供其他人使用,因此ProcessFiles将被编码为MyAddIn.ProcessFiles。