仅打开指定的工作簿

时间:2015-12-13 15:52:53

标签: excel excel-vba vba

我每天运行此代码会影响目录中的每个.xlsx工作簿,但如果文件名不在“Okay”数组中,如何忽略工作簿?

这是我目前的语法:

Option Explicit
Public Sub OpenExcelInDir()
Dim MyFolder As String
Dim MyFile As String
    MyFolder = "C:\ExcelSheets"
    MyFile = Dir(MyFolder & "\*.xlsx")
    Do While MyFile <> ""
        Workbooks.Open Filename:=MyFolder & "\" & MyFile
        MyFile = Dir
        Call UpdateAllSheets
    Loop
End Sub

现在我想改变它,以便我可以声明一个字符串数组,只打开数组中的工作簿:

Dim goodWB() As String
goodWB= Split("ABC123,DEF456,GHI789", ",")

3 个答案:

答案 0 :(得分:2)

即使我喜欢IsInArray函数,我认为该算法效率极低。如果该文件夹中有1000个文件,则如果少数给定文件名中的一个匹配,则将创建1000个临时数组。此外,我希望在打开一个想要的文件之后,代码将不再测试此名称(事实并非如此)。 相反,我建议从另一端看问题:

Public Sub OpenExcelInDir()
    Dim goodWB, filename
    Dim MyFolder As String
    Dim MyFile As String

    goodWB = Array("ABC123.xls", "DEF456.xlsx", "GHI789.xlsx")
    MyFolder = "C:\ExcelSheets"

    For Each filename In goodWB
        MyFile = MyFolder & "\" & filename
        If Len(Dir(MyFile)) > 0 Then
            Workbooks.Open filename:=MyFile
            Call UpdateAllSheets
        End If
    Next WB
End Sub

此处,Dir()函数用于测试指定文件夹中所需文件名的存在性。作为一个额外的优势,他/她的评论中提到的EEM不会有任何含糊之处。

答案 1 :(得分:1)

我认为这将满足您的要求。我添加了一行来测试文件名是否与数组中的文件名匹配。

<强>测试

Option Explicit
Public Sub OpenExcelInDir()
Dim goodWB() As String
goodWB = Split("ABC123.xlsx,DEF456.xlsx,GHI789.xlsx", ",")
Dim MyFolder As String
Dim MyFile As String
MyFolder = "C:\ExcelSheets"
MyFile = Dir(MyFolder & "\*.xlsx")
Do While MyFile <> ""
    If IsInArray(MyFile, goodWB) Then
        Workbooks.Open Filename:=MyFolder & "\" & MyFile
        MyFile = Dir
        Call UpdateAllSheets
    End If
    MyFile = Dir
Loop
End Sub

Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
  IsInArray = (UBound(Filter(arr, stringToBeFound)) > -1)
End Function

答案 2 :(得分:1)

Public Sub OpenExcelInDir()
Const kExt As String = ".xlsm"      `As extension is fixed it could be defined as a constant to avoid repetition
Dim aWbks As Variant, vItm As Variant   ‘Suggest to define the array in one step choose the form you prefer
‘aWbks = Array("ABC123", "DEF456", "GHI789")
aWbks = [{"ABC123", "DEF456", "GHI789"}]

Dim MyFolder As String
Dim MyFile As String
    MyFolder = "C:\ExcelSheets"
    MyFile = Dir(MyFolder & "\*" & kExt)

    Do While MyFile <> ""
        For Each vItm In aWbks
            If vItm & kExt = MyFile Then
                Workbooks.Open Filename:=MyFolder & "\" & MyFile
                Call UpdateAllSheets
                Exit For
        End If: Next
        MyFile = Dir
    Loop
End Sub