To create a new code to achieve the goal of selecting a new workbook to run a macro saved in current workbook
时间: 2024-02-27 20:52:38 浏览: 72
Sure, I can help you with that. Here's a sample code that you can use to select a new workbook and run a macro saved in the current workbook:
```
Sub RunMacroInNewWorkbook()
Dim wb As Workbook
Dim newWb As Workbook
Dim macroName As String
' Get the name of the macro to run
macroName = "MyMacro"
' Select a new workbook
Set newWb = Application.Workbooks.Open("C:\Path\To\NewWorkbook.xlsx")
' Run the macro in the new workbook
newWb.Application.Run "'" & ThisWorkbook.Name & "'!" & macroName
' Close the new workbook
newWb.Close False
' Set the focus back to the current workbook
ThisWorkbook.Activate
End Sub
```
In this code, you first define the name of the macro that you want to run (`macroName`). Then, you select a new workbook using the `Workbooks.Open` method and store it in the `newWb` variable.
Next, you use the `Run` method of the `Application` object to run the macro in the new workbook. The syntax for this is `"'" & ThisWorkbook.Name & "'!" & macroName`, where `ThisWorkbook.Name` is the name of the current workbook and `macroName` is the name of the macro.
After the macro has been run in the new workbook, you close it using the `Close` method. Finally, you set the focus back to the current workbook using the `Activate` method.
I hope this helps! Let me know if you have any other questions.
阅读全文