我的工作是關於每天格式化100個文件。雖然我有一個爲此目的而設計的宏,但是我必須在保存之前的每個文件上運行宏。在任務欄中打開的所有文件上逐一運行宏
我的問題是我如何能夠在這些打開的工作簿上一步運行我的宏。當我保存一個它會在隊列中的另一個上運行。
我的工作是關於每天格式化100個文件。雖然我有一個爲此目的而設計的宏,但是我必須在保存之前的每個文件上運行宏。在任務欄中打開的所有文件上逐一運行宏
我的問題是我如何能夠在這些打開的工作簿上一步運行我的宏。當我保存一個它會在隊列中的另一個上運行。
我有我的解決使用下面的代碼。
Sub OpenAllWorkbooksnew()
Set destWB = ActiveWorkbook
Dim DestCell As Range
Dim cwb As Workbook
For Each cwb In Workbooks
**Call donemovementReport**
ActiveWorkbook.Close True
ActiveWorkbook.Close False
Next cwb
End Sub
把下面的宏在「基地」工作簿Passerby提到
Sub SO()
Dim macroList As Object
Dim workbookName As String
Dim wbFullPath
Dim macroName As String
Dim currentWb As Workbook
Dim masterWb As Workbook ' the Excel file you are calling this procedure from
Dim useWbList As Boolean
Dim height As Long, i As Long
Dim dataArray As Variant
useWbList = False ' DEFINE which input method
Set macroList = CreateObject("Scripting.Dictionary")
If useWbList Then
' you can also from the dictionary from 2 columns of an excel file , probably better for management
With masterWb.Worksheets("Sheet1") '<~~ change Sheet1 to the sheet name storing the data
height = .Cells(.Rows.Count, 1).End(xlUp).Row ' Assume data in column A,B, starting from row 1
If height > 1 Then
ReDim dataArray(1 To height, 1 To 2)
dataArray = .Range(.Cells(1, 1), .Cells(height, 2)).Value
For i = 1 To height
macroList.Add dataArray(i, 1), dataArray(i, 2)
Next i
Else
'height = 1 case
macroList.Add .Cells(1, 1).Value, .Cells(1, 2).Value
End If
End With
Else
' ENTER THE FULl PATH in 1st agrument below, Macro Name in 2nd argument
' Remember to make sure the macro is PUBLIC, try to put them in Module inside of Sheets'
macroList.Add "C:\Users\wangCL\Desktop\Book1.xlsm", "ThisWorkbook.testing"
'macroList.Add "FULL PATH", "MACRO NAME"
'macroList.Add "FULL PATH", "MACRO NAME"
'macroList.Add "FULL PATH", "MACRO NAME"
End If
Application.DisplayAlerts = False
For Each wbFullPath In macroList.keys
On Error GoTo 0
macroName = macroList.Item(workbookName)
workbookName = Mid(wbFullPath, InStrRev(wbFullPath, "\") + 1)
Err.Clear
On Error Resume Next
Set currentWb = Nothing
Set currentWb = Workbooks(workbookName) ' see if the workbook is already open
If Err.Number <> 0 Then
' open the workbook if workbook NOT opened
Set currentWb = Workbooks.Open(workbookName, ReadOnly:=True)
End If
On Error GoTo 0
' run the macro
Application.Run workbookName & "!" & macroList.Item(wbFullPath)
'close the workbook after running the macro
currentWb.Close saveChanges:=False
Set currentWb = Nothing
Next wbFullPath
End Sub
希望它可以幫助並請讓我知道如果有什麼不清楚的地方
該代碼看起來不錯。爲了便於使用,我將從專用的「主」excel文件創建宏模型。 另外,如果遇到錯誤,我不會簡單地繼續工作,但可以寫出某種警告,因此您不必檢查每個工作簿是否有錯誤。 –
@ChristianSauer感謝您的建議,更新代碼 – Larry
我失敗的步驟,我必須定義我的宏名稱? – user1960257
您可以使用類似於「Workbooks.Open」的內容從「基本」工作簿打開工作簿並操作其內容。 – Passerby