我有一个由多个宏组成的主宏工作簿,基本上它由一个生成单独文件工作表组成,其中有一个下拉列表用于选择特定值,并且该单元格旁边有一个按钮用于为所选值运行宏。
因此,当我在“生成文件”工作表单元格中选择值并单击“运行宏”按钮时,它首先使用我在单元格中选择的名称/值将主宏文件本身另存为,然后过滤掉来自的数据主宏工作簿中的每个工作表仅保留所选值的数据。
因此,我必须多次打开主宏文件工作簿,选择“生成单独文件”工作表单元格中的值,然后单击“运行宏”。我想创建另一个宏工作簿,它可以打开主宏工作簿,在“生成单独的文件工作表”的验证下拉列表中选择值,并为每个值运行宏并为每个选定的文件生成单独的文件。
Sub Runmasterfilemacros ()
Dim wb1 as workbook
Dim wb2 as workbook
Dim sht1 as worksheet
Dim sht2 as worksheet
Dim myrange as Range
Set wb1 = ThisWorkbook
Set wb2 = ThisWorkbook.Sheets("Run Macro").Range("A2").Value
' This Workbook Run Macro Range A2 value = "c:\macrofiles\Master Macro File.xlsm"
Set sht1 = ThisWorkbook.Sheets("Run Marco")
Set sht2 = Workbooks("Master Macro File").Sheets("Generate Separate Files")
Set myrange = Workbooks("Master Macro File").Sheets("Generate Separate Files").Range("A11").Value
wb2.Select
sht2.select
myrange.select
myrange.value = "File1"
Application.Run "File1Macro"
'wait for the macro to run and the workbook to get saved as File1 then run another macro
wb1.Activate
wb2.Select
sht2.select
myrange.select
myrange.value = "File2"
Application.Run "File2Macro"
'wait for the macro to run and the workbook to get saved as File2 then run another macro
wb2.Select
sht2.select
myrange.select
myrange.value = "File3"
Application.Run "File3Macro"
'wait for the macro to run and the workbook to get saved as File3 then run another macro
wb2.Select
sht2.select
myrange.select
myrange.value = "File4"
Application.Run "File4Macro"
'wait for the macro to run and the workbook to get saved as File4 then run another macro
wb2.Select
sht2.select
myrange.select
myrange.value = "File5"
Application.Run "File5Macro"
'wait for the macro to run and the workbook to get saved as File5 then run another macro
'This needs to run for all the values which are in the validation dropdown of myrange .i.e. 25 files
End Sub
例如:
Sub Runmasterfilemacros()
Dim wb1 As Workbook, wb2 As Workbook, sht1 As Worksheet
Dim dvRange As Range, listRange As Range, c As Range
Set wb2 = Workbooks("Master Macro File.xlsm") 'safer to include the extension
Set dvRange = wb2.Worksheets("Generate Separate Files").Range("A11") 'cell with drop-down
Set listRange = wb2.Worksheets("Lists").Range("A2:A26") 'for example; your list of values
For Each c In listRange.Cells 'loop the range of list values
dvRange.Value = c.Value 'set a value
Application.Run "'" & wb2.Name & "'!FileExportMacro" 'run the macro
Next c
End Sub