如何使用部分已知的名称将变量分配给Excel工作表

时间:2018-10-08 11:41:29

标签: excel vba excel-vba

有人可以为我提供以下帮助:

我遇到“ Set ch1 =”问题

文件名(或者文件名的后几个字符每天都会稍有变化),因此我需要添加通配符(*)或类似的东西。

如何为文件设置“ ch1 =“,其名称会发生​​变化?

这是我开发的代码的一部分。

Option Explicit
Sub Open_Latest_Cheque()
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Call Open_Latest_File

Dim ch1 As Workbook, AC As Workbook, temp As Workbook
Dim ch1ws As Worksheet, ACws As Worksheet
Dim ACwsLR As Long, tempName As String

**Set ch1 = Workbooks("Sum100123.csv")**
Set ch1ws = ch1.Sheets(1)
Set AC = Workbooks("Mon.xlsm")
Set ACws = AC.Sheets("Data")

Dim MyPath  As String, MyFile  As String, LatestFile  As String
Dim LatestDate  As Date, LMD  As Date.............

谢谢

2 个答案:

答案 0 :(得分:1)

尝试一下:

Sub test_partial_name()

Dim pt_nm As Workbook

For Each pt_nm In Application.Workbooks
   If (pt_nm.Name) Like "Sum1#123.csv" Then
Exit For
End If

Next pt_nm
   If Not pt_nm Is Nothing Then
   pt_nm.Activate
Else
MsgBox "The file has not opened!"
End If

With Sheets(1)

Cells(1, 1).Value = "its working? Yes"

End With

答案 1 :(得分:0)

一种方法是使用For Each wkb in Workbooks遍历工作簿的集合,并使用Like检查每个迭代的工作簿的名称。在这里,您可以使用*#?等(请参见屏幕截图)。找到所需内容后,将其分配给wbkSpecific并使用Exit For退出集合:

Sub TestMe()

    Dim wkb As Workbook
    Dim wkbSpecific As Workbook

    For Each wkb In Workbooks
        If wkb.Name Like "Sum1*???.csv" Then
            Set wkbSpecific = wkb
            Exit For
        End If
    Next wkb

    If Not wkbSpecific Is Nothing Then
        MsgBox wkbSpecific.Name
    End If

End Sub

enter image description here