VBA recognizing workbook by partial name

后端 未结 2 659
悲哀的现实
悲哀的现实 2021-01-03 10:10

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 futu

2条回答
  •  再見小時候
    2021-01-03 10:59

    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.

提交回复
热议问题