簡體   English   中英

如何將變量分配給具有部分已知名稱的Excel工作表

[英]How to assign variable to an Excel worksheet with a partially known name

有人可以幫我解決以下問題:

我有一個問題“ 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.............

謝謝

嘗試這個:

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

一種方法是使用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

在此輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM