我正在尝试编写一些VBA代码,以在打开该文件时触发另一个文件中的另一个宏。
我编写了以下代码,但不确定打开文件后如何进行。 (我尝试在xWB中触发的宏称为“ Sub Button_Click()”) 此宏当前分配给一个按钮-因此,我为什么要挣扎。
Sub Openworkbook_click()
Dim xWb As Workbook
Dim MainBook As Workbook
On Error Resume Next
Application.DisplayAlerts = False
Set xWb = Workbooks.Open("C:link to other file")
Application.DisplayAlerts = True
If Err.Number <> 0 Or xWb Is Nothing Then
On Error GoTo 0
MsgBox "The filepath for the borkbook to run the Macro is wrong - please
update", vbCritical, "Wrong path"
GoTo Finish 'Skips down to close
Else
On Error GoTo 0 'Re-enables errors
End If
Application.Run "'" & xWb.Name & "'!Sub Button_Click()"
'Close workfie
xWb.Close False 'Closes the workbook with the macro, doesn't save
Finish:
Set xWb = Nothing
'Finish on NXD Tab
ActiveWorkbook.Sheets("NXD Report").Activate
End Sub
有人可以帮我触发宏吗?
答案 0 :(得分:1)
如果宏与_click
动作相关联,则无法触发该宏。
您可以创建一个由_click
操作调用的子,也可以由VBA从代码中调用。
您可以通过以下方式使用VBA对其进行调用:
str = xWb.Name & "!" & "Macro_For_NXD" 'Create string with file name and add the name of macro
Application.Run str
注意:“ Macro_For_NXD”是被调用的工作簿中宏的名称
答案 1 :(得分:1)
您可以如上所述单击,或者可以执行以下操作:
Sub Openworkbook_click()
Dim xWb As Workbook
Dim MainBook As Workbook
On Error Resume Next
Application.DisplayAlerts = False
Set xWb = Workbooks.Open("C:my file link")
Application.DisplayAlerts = True
If Err.Number <> 0 Or xWb Is Nothing Then
On Error GoTo 0
MsgBox "The filepath for the borkbook to run the Macro is wrong - please update", vbCritical, "Wrong path"
GoTo Finish 'Skips down to close
Else
On Error GoTo 0 'Re-enables errors
End If
Set MainBook = Workbooks.Open("C:my current file") 'Not sure what this is for but you may have a use for it.
Application.Run "'" & xWb.Name & "'!Sub Button_Click()"
xWb.Close False 'Closes the workbook with the macro, doesn't save
Finish:
Set xWb = Nothing
Set MainBook = Nothing
End Sub