【问题标题】:Using a wildcard to open an excel workbook使用通配符打开 Excel 工作簿
【发布时间】:2013-10-31 21:17:04
【问题描述】:

我想使用通配符打开存储在与我的宏工作簿相同的文件夹中的工作簿。文件夹中有一个名为302113-401yr-r01.xlsm 的文件。这是我的代码:

Workbooks.Open filename:=ActiveWorkbook.Path & "\302113*.xlsm"

但是,它告诉我没有这样的文件。有什么建议吗?

【问题讨论】:

  • 您不能在路径或文件名中使用星号。您需要分别打开每个文件。在 SO 中搜索“Dir function”,肯定有很多例子。 HERE你也找到了一些信息。

标签: excel wildcard vba


【解决方案1】:

我还没有使用 Excel 的经验,但以下内容对我来说非常适合在文件名中使用通配符来打开文件。此示例要求所有文件位于同一目录/文件夹中。是的,它非常简单。

Sub using_wildcards_to_open_files_in_excel_vba()

    Dim mypath As String
    Dim sFilename As String

    'Suppose you have three files in a folder
    ' Named blank.xlsx,, ex1_939_account.xlsx,  and ex1_opt 5.xlsx

    'Manually open the blank.xlsx file

    'The following code lines will open the second two files before closing the previously opened file.

    ActiveWorkbook.Activate
    mypath = ActiveWorkbook.Path
    'opening xlsx file with name containing "939" and closing current file
    mypath = mypath & "\*939*.xlsx"
    'MsgBox mypath  'Checking
    sFilename = Dir(mypath)
    'MsgBox sFilename  'Checking

    ActiveWorkbook.Close savechanges:=False
    Workbooks.Open Filename:=sFilename

    ActiveWorkbook.Activate
    mypath = ActiveWorkbook.Path
    'opening xlsx file with name ending in "opt 5" and closing current file
    mypath = mypath & "\*opt 5.xlsx"
    'MsgBox mypath  'Checking
    sFilename = Dir(mypath)
    'MsgBox sFilename  'Checking

    ActiveWorkbook.Close savechanges:=False
    Workbooks.Open Filename:=sFilename

End Sub

【讨论】:

    【解决方案2】:

    您可以使用通配符打开文件,但出于某种原因只能使用 UNC 路径。

    例如:

    Set xlFile = xlObj.WorkBooks.Open("\\yourServerHere\dataAutomation\*.xlsx")
    

    【讨论】:

    • 这种方法对我不起作用,请取消我的投票(已锁定)。
    【解决方案3】:

    根据我的经验,如果您将通配符/asterix 作为字符串中的最后一个符号并且只有一个文件,则此方法有效。尝试做:

    Workbooks.Open filename:=ActiveWorkbook.Path & "\302113*"
    

    例如我正在使用:

    Workbooks.Open Filename:="X:\business\2014\Easy*"
    

    它有效。

    【讨论】:

      【解决方案4】:

      我们无法使用通配符打开文件 - 如果可以的话,想象一下混乱吧!

      您需要使用Dir(ActiveWorkbook.Path & "\302113*.xlsm") 来循环访问返回的文件。如果只有一个,那么只需使用此功能一次:

      Dim sFound As String
      
      sFound = Dir(ActiveWorkbook.Path & "\302113*.xlsm")    'the first one found
      If sFound <> "" Then
          Workbooks.Open filename:= ActiveWorkbook.Path & "\" & sFound
      End If
      

      Dir Function :网上科技

      【讨论】:

      • + 1 We cannot open a file using a wildcard - imagine the chaos if we could! 如此真实:)
      • 啊,我知道使用通配符打开文件会有问题。感谢您的回复!
      • 只有一条评论,除非我弄错了,似乎DIR函数只返回文件名,而不是路径和文件名。所以当我在上面的代码中使用 Workbooks.Open 时,我不得不使用:ActiveWorkbook.Path & "\" & sFound
      • 感谢您的回复,我已将此添加到答案中,以防其他人发现它有用。
      • 我不明白为什么评论 the chaos 似乎所有其他编程语言都支持通配符,由编码人员来编写逻辑,而不是语言。
      猜你喜欢
      • 1970-01-01
      • 2014-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-10
      • 2015-06-02
      相关资源
      最近更新 更多