代码之家  ›  专栏  ›  技术社区  ›  David Erickson

打开文件名相似的Excel文件时是否有自动运行宏的方法?

  •  1
  • David Erickson  · 技术社区  · 7 年前

    我做了大量的研究,今天下午自己试了一下,但没有成功。当用户下载并打开以“当前已批准”开头的.xls文件时,我希望宏在打开时从“个人.xlsb”文件自动运行在任何“当前已批准的*.xls”文件上(*是通配符)。这样,我就可以一次性将代码放入任何给定用户的“personal.xlsb”文件中,并且宏将自动触发,而用户无需记住通过快捷键或按钮触发宏。

    从我的研究 here 在其他地方,我只看到了以下方法:

    1. 打开包含宏的工作簿时运行宏。
    2. 打开任何工作簿时运行宏。

    我试图从上面的链接中修改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
    

    实际上,如果我从CRM下载一个以“当前已批准”开头的Excel文件并打开它,我希望看到一个“测试”的消息框。

    1 回复  |  直到 7 年前
        1
  •  1
  •   PGSystemTester    7 年前

    你的代码与你描述的不一样。下面的代码应显示“测试” MsgBox 打开符合从“当前已批准”开始规则的工作簿时

    'This Macro will run whenever an Excel Workbooks is opened
    Private Sub MonitorApp_WorkbookOpen(ByVal Wb As Workbook)
        Dim cText As String
        cText = "Current Approved"
    
        If UCase(Left(Wb.Name, Len(cText))) = UCase(cText) Then
               ' Wb2.Activate
                MsgBox "Test"
        End If
    
    End Sub
    
    推荐文章