简体   繁体   English

有没有办法在打开具有相似文件名的 Excel 文件时自动运行宏?

[英]Is there a way to automatically run a macro upon opening Excel files with similar file names?

I have researched a good amount and tried this on my own this afternoon but was unsuccessful.我已经研究了很多,今天下午自己尝试了这个,但没有成功。 When users download and open .XLS files that begin with "Current Approved", I want a macro to automatically run from my "PERSONAL.XLSB" file on any "Current Approved*.XLS" file upon opening it (* is a Wildcard).当用户下载并打开以“Current Approved”开头的 .XLS 文件时,我希望在打开任何“Current Approved*.XLS”文件时自动从我的“PERSONAL.XLSB”文件运行一个宏(* 是通配符) . That way I can just put the code in any given users "PERSONAL.XLSB" file one time, and the macro will just automatically be triggered without the user needing to remember to trigger the macro via a shortcut key or button.这样我就可以一次性将代码放入任何给定用户的“PERSONAL.XLSB”文件中,并且宏将自动触发,用户无需记住通过快捷键或按钮触发宏。

From my research here and in other places, I have only seen ways to:从我在这里和其他地方的研究来看,我只看到了以下方法:

  1. Run the macro when opening the workbook which contains the macro.打开包含宏的工作簿时运行宏。
  2. Run a macro when any workbook is opened.打开任何工作簿时运行宏。

I have tried to modify #2 from the link above, but I've NOT figured out how to automatically run macros in this manner on files with similar names.我试图从上面的链接修改 #2,但我还没有想出如何以这种方式在具有相似名称的文件上自动运行宏。

'Declare the application event variable
Public WithEvents MonitorApp As Application

'Set the event variable be the Excel Application
Private Sub Workbook_Open()
    Set MonitorApp = Application
End Sub

'This Macro will run whenever an Excel Workbooks is opened
Private Sub MonitorApp_WorkbookOpen(ByVal Wb As Workbook)
    Dim Wb2 As Workbook

    For Each Wb2 In Workbooks
        If Wb2.Name Like "Current Approved*" Then
            Wb2.Activate
            MsgBox "Test"
        End If
    Next
End Sub

Essentially, if I download an excel file from our CRM that begins with "Current Approved" and open it, I would like to see a messagebox of "Test".本质上,如果我从我们的 CRM 下载一个以“Current Approved”开头的 excel 文件并打开它,我希望看到一个“Test”的消息框。

Your code doesn't look like what you're describing.您的代码看起来不像您所描述的那样。 The below code should display the "Test" MsgBox when opening workbooks meeting the rule of starting with "Current Approved"当打开符合以“当前已批准”开头的规则的工作簿时,以下代码应显示“测试” MsgBox

'This Macro will run whenever an Excel Workbooks is opened
Private Sub MonitorApp_WorkbookOpen(ByVal Wb As Workbook)
    Const cText As String = "Current Approved"

    If UCase(Left(Wb.Name, Len(cText))) = UCase(cText) Then
           ' Wb2.Activate
            MsgBox "Test"
    End If

End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM