[英]How to assign variable to an Excel worksheet with a partially known name
Can someone help me with the following: 有人可以帮我解决以下问题:
I have an issue with " Set ch1 =
" 我有一个问题“ Set ch1 =
”
The file name (or rather the last few characters of its name change slightly everyday), thus I need to add wildcard (*) or something similar. 文件名(或者说其名称的最后几个字符每天稍有变化),因此我需要添加通配符(*)或类似的东西。
How do I do "Set ch1 =" with a file, which name changes? 如何使用文件更改“设置ch1 =”?
Here is part of the code I have developed. 这是我开发的代码的一部分。
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.............
Thanks 谢谢
Try this: 尝试这个:
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
A way to do it is to loop through the collection of workbooks with For Each wkb in Workbooks
and to check the name of every iterated workbook with Like
. 一种方法是使用For Each wkb in Workbooks
遍历工作簿集合,并使用Like
检查每个迭代工作簿的名称。 There, you may use *
, #
, ?
在那里,你可以使用*
, #
?
, etc (see the screenshot). 等等(见截图)。 Once you find what you need assign it to the wbkSpecific
and exit the collection with Exit For
: 找到需要的内容后,将其分配给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.