VBA – 如何search活动工作簿,并匹配string的文件名?

我正在编写一个快速的自动化项目工作,我不能指定一个文件path来打开一个工作簿,因为它是在一个特殊的软件中使用,不容易用VBA访问。

如果用户A打开此文件:“ABC_todaysdate”…我如何告诉Excel循环通过活动工作簿(用户A可以有5-6个工作簿打开),在Activeworkbook文件名中find字母ABC,并使用rest我的function?

VBA代码到目前为止:

Sub CopyDemand() Dim filename As String Dim Wb As Workbook Dim ws As Worksheet Dim Wb2 As Workbook Set Wb = ThisWorkbook For Each Wb2 In Application.Workbooks filename = ActiveWorkbook.FullName If filename Like "demand" Then Debug.Print ("Found") ''' Insert function to use WB2 and copy over data, compare workbooks etc. Next Wb.Activate End Sub 

您可以迭代每个工作簿,但是我认为这里的关键是使工作簿处于活动状态,以便您可以使用path信息检索FullName。

 Option Explicit Function getWbName(SearchStr As String) As String On Error GoTo ErrHand: Application.ScreenUpdating = False Dim wb As Workbook getWbName = vbNullString For Each wb In Workbooks If InStr(1, wb.Name, SearchStr, vbTextCompare) > 0 Then wb.Activate getWbName = ActiveWorkbook.FullName Exit For End If Next 'Return the active window and exit ThisWorkbook.Activate Application.ScreenUpdating = True Exit Function ErrHand: Application.ScreenUpdating = True MsgBox (Err.Number & " has occured, with description: " & Err.Description) End Function Sub Example() Debug.Print getWbName("Book2") End Sub 

编辑

更新上面的代码来返回WorkBook对象。

 Option Explicit Function getWorkBookByName(SearchStr As String) As Workbook Dim wb As Workbook For Each wb In Workbooks If InStr(1, wb.Name, SearchStr, vbTextCompare) > 0 Then Set getWorkBookByName = wb Exit Function End If Next End Function Sub Example() Dim myWb As Workbook: Set myWb = getWorkBookByName("Book2") If Not myWb Is Nothing Then Debug.Print myWb.FullName End Sub 

您可以尝试捕获应用程序对象的WorkbookOpen事件。

这是一种方法:将以下代码复制到主工作簿的ThisWorkbook对象中。

 Option Explicit Private WithEvents myApp As Application Private Sub myApp_WorkbookOpen(ByVal Wb As Workbook) MsgBox "Openned " & Wb.FullName End Sub Private Sub Workbook_Open() Set myApp = Application End Sub 

然后closures你的工作簿,并重新打开,如果启用macros。 此工作簿的名称以及随后打开的每个后续工作簿都将显示在消息框中。