从其名称开始查找工作簿

我在获取消息框时遇到了一些问题

Sub FindingNewWBNAme() For Each Wb In Application.Workbooks ' I'm activating all open workbooks If Left(Wb.Name, 6) = "CA-DIS" Then ' i want to find particular workbook MsgBox "Found" 'Incase find i need found message box End If If Left(Wb.Name, 6) <> "CA-DIS" Then 'Incase not find i need not found MsgBox "Not Found" End If Next End Sub 

此外,我需要工作簿与WBK 1或WBK2等特殊名称睡觉。

我尝试着

 Dim WB as workbook Dim WBK1 as workbook Set WBK1 = "CA-DIS" '----> i have found this name using first 6 letters 

 Sub GetWorkbookByHeader() Dim wb As Workbook Dim wbDis As Workbook For Each wb In Application.Workbooks If UCase(wb.Name) Like "CA-DIS*" Then 'OR:' If UCase(Left(Trim(wb.Name), 6)) = "CA-DIS" Then Set wbDis = wb Exit For End If Next ' Exit if no matching workbook was found. If wbDis Is Nothing Then MsgBox "No Disb workbook!" Exit Sub End If 'We have a matching workbook (stored in wbDis), continue: ... ' ===>>> You were getting an error because wbDis was "nothing" and therefore did not have a worksheets(1) property. End Sub 

添加到Siddharth Rout的答案:您也可以使用“like”操作符(它更灵活,更易于更改和根据您的具体需求量身定制):

 UCase(wb.Name)) like "CA-DIS*" 

*是一个通配符,可以用来匹配任何string。

您也可以使用其他通配符,如:

? – 匹配单个字符(您可以重复匹配特定数量的字符)

[0-9] – 仅匹配数字(您可以进一步限制数字范围,例如匹配从1到3的ONY号码[1-3]

[Az] – 仅匹配字母(再次可以限制范围,例如AZ仅用于大写字母,或者[az]仅用于小写字母)。

有无数的组合可以让你匹配特定的模式,例如:

[a-cA-C] – 匹配集合{A,B,C,a,b,c}中的字符

[0-5a-cA-C] – 匹配集合{1,2,3,4,5,A,B,C,a,b,c}中的字符

您可以拒绝括号内的模式: [!a] – 匹配“a”

不要忘记,如果您需要匹配星号( * )或其他“特殊”字符,您需要将它们括在括号内: [*] – 字面上匹配星号

这真的是一个强大的工具(如果你需要更多的权力,你可以检查正则expression式,如果你添加了合适的参考,可以在Visual Basic中使用)。

更多信息: https : //docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/operators/like-operator

未经testing

这是你正在尝试?

 Sub Sample() Dim wb As Workbook Dim WBK1 As Workbook For Each wb In Application.Workbooks If UCase(Left(Trim(wb.Name), 6)) = "CA-DIS" Then Set WBK1 = wb Exit For End If Next If Not WBK1 Is Nothing Then With WBK1 '~~> Do what you want End With Else MsgBox "Workbook CA-DIS not found" End If End Sub 

说明

  1. Trim(wb.Name)修剪前导和尾随空格。
  2. Left(Trim(wb.Name), 6)将给你6个字符,你正在寻找
  3. UCase(Left(Trim(wb.Name), 6))会将其转换为大写。