VBA recognizing workbook by partial name

偶尔善良 提交于 2019-12-03 21:55:21

问题


Is there a way to specify a workbook for a sheet without having the full name? For example, If the workbook name is MyWorbook2015 and the 2015 may change to 2016 in the future, I need to to recognize the workbook based on MyWorkbook, and ignore the 2015. Something similar to this:

With Workbooks("MyWorkbook2015").Sheets("My_Sheet_Name_That_Does_Not_Change")
     'do something
End With

In the code sample above, I need it to recognize the work book regardless of the date? Is this possible? If it is, how would I go about doing that?


回答1:


Yes you can use the LIKE Operator with a wildcard "*". Here is an example. I am assuming that the workbook is open.

Sub Sample()
    Dim wb As Workbook
    Dim wbName As String

    '~~> "MyWorkbook2015"
    wbName = "MyWorkbook"

    For Each wb In Application.Workbooks
        If wb.Name Like wbName & "*" Then
            Debug.Print wb.Name

            With wb.Sheets("My_Sheet_Name_That_Does_Not_Change")
                '~~> Do something
            End With
        End If
    Next wb
End Sub

EDIT

Here is a way where you can use it as a function

Dim wbName As String

Sub Sample()
    '~~> "MyWorkbook2015"
    wbName = "MyWorkbook"

    If Not GetWB Is Nothing Then
        Debug.Print GetWB.Name
        With GetWB.Sheets("My_Sheet_Name_That_Does_Not_Change")
            '~~> Do something
        End With
    Else
        MsgBox "No workbook with that name found"
    End If
End Sub

Function GetWB() As Workbook
    Dim wb As Workbook

    For Each wb In Application.Workbooks
        If wb.Name Like wbName & "*" Then
            Set GetWB = wb
            Exit Function
        End If
    Next wb
End Function



回答2:


A slightly more reliable alternative to doing a partial match on Workbook.Name is to do an equivalency match on WorkBook.CodeName. The default CodeName for a Workbook is "ThisWorkbook", but you can change that by selecting the "ThisWorkbook" code page in the Project Explorer window and then open the Properties Window (Key: F4) and change the Name property for the code page.

Then following the example that Siddharth has shown but redefining then "GetWB" function like this:

Function GetWB() As Excel.Workbook
    Const wbCodeName As String = "MySecretWorkbookName"   ' change to the CodeName you choose

    Dim wb As Workbook
    For Each wb In Application.Workbooks
        If wb.CodeName = wbCodeName Then
            Set FindWorkbook = wb
            Exit For
        End If
    Next wb
End Function

Note that changing the CodeName allows you to use the new CodeName in places where you would have used "ThisWorkbook", but you can still use "ThisWorkbook" as well.



来源:https://stackoverflow.com/questions/30358293/vba-recognizing-workbook-by-partial-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!