VBA通过部分名称识别工作簿

时间:2015-05-20 19:04:16

标签: excel vba excel-vba excel-2010

有没有办法在没有全名的情况下为工作表指定工作簿? 例如,如果工作簿名称是MyWorbook2015,2015年可能会更改为2016年,我需要基于MyWorkbook识别工作簿,并忽略2015年。类似于此:

Glu.gluUnProject(tempx, viewport[3] - tempy, 0, modelMatrix, projMatrix, viewport, out x1, out y1, out z1);
            p = new Point(x1, y1, z1);
            Glu.gluUnProject(tempx, viewport[3] - tempy, 1, modelMatrix, projMatrix, viewport, out x1, out y1, out z1);
            p1 = new Point(x1, y1, z1);

在上面的代码示例中,无论日期如何,我都需要它来识别工作簿?这可能吗?如果是的话,我该怎么做呢?

2 个答案:

答案 0 :(得分:3)

是的,您可以将LIKE运算符与通配符“*”一起使用。这是一个例子。我假设工作簿是开放的。

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

修改

这是一种可以将其用作函数的方法

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

答案 1 :(得分:1)

在Workbook.Name上进行部分匹配的稍微更可靠的替代方法是在WorkBook.CodeName上进行等效匹配。工作簿的默认CodeName是" ThisWorkbook",但您可以通过选择" ThisWorkbook"来更改它。 Project Explorer窗口中的代码页,然后打开Properties窗口(Key:F4)并更改代码页的Name属性。

然后按照Siddharth展示的例子,然后再重新定义" GetWB"功能如下:

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

请注意,更改CodeName允许您在使用过的地方使用新的CodeName" ThisWorkbook",但您仍然可以使用" ThisWorkbook"同样。