VBA打开其中包含特定关键字的文件

时间:2018-01-03 16:45:37

标签: excel vba excel-vba

我有一个文件夹,里面有一堆.xls个文件,其中只有那些有KEY Word"城市"对我很感兴趣。我需要打开这些文件并收集一些信息,我面临一些问题。

Sub getTheExecSummary()

Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim FldrPicker As FileDialog


myPath = "C:\Users\Morpheus\Documents\Projects\Files"



myExtension = "*.xls"  'How to add the keyword?'

myFile = Dir(myPath & myExtension)


Do While Len(myFile) > 0
    'Set variable equal to opened workbook
    Set wb = Workbooks.Open(Filename:=myPath & myFile)
    Debug.Print (myFile)
    Debug.Print (wb.Name)
    ActiveSheet.Range("A1").Value = wb.Name
    'Get next file name
      myFile = Dir
Loop

End Sub 

我确实写了一些Debug.Print语句,但似乎都没有。我现在想要只打印那些包含关键字'城市'以他们的名义。

2 个答案:

答案 0 :(得分:2)

我认为你想要Instr功能。

If Instr(wb.Name, "CITIES") > 0 then .....

您可能希望使用“CITIES”或“CITIES”排除对这些字母的任何无意使用,具体取决于文件名的设置方式

答案 1 :(得分:0)

如果您期待xlsx,xlsm等,请使用通配符标识缺失的字母:*CITIES*.xls*CITIES*.xls*

Sub Test()

    Dim colFiles As Collection
    Dim vItem As Variant
    Dim wrkBk As Workbook
    Dim sPath As String

    Set colFiles = New Collection

    sPath = "C:\Users\Morpheus\Documents\Projects\Files\"
    'you could use:
    'sPath = Environ("UserProfile") & "\Documents\Projects\Files\"

    EnumerateFiles sPath, "*CITIES*.xls", colFiles

    For Each vItem In colFiles
        Set wrkBk = Workbooks.Open(vItem)
        wrkBk.Worksheets("Sheet1").Range("A1") = wrkBk.Name
    Next vItem

End Sub

Sub EnumerateFiles(ByVal sDirectory As String, _
    ByVal sFileSpec As String, _
    ByRef cCollection As Collection)

    Dim sTemp As String

    sTemp = Dir$(sDirectory & sFileSpec)
    Do While Len(sTemp) > 0
        cCollection.Add sDirectory & sTemp
        sTemp = Dir$
    Loop
End Sub