Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
915 views
in Technique[技术] by (71.8m points)

excel - VBA recognizing workbook by partial name

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...