如何使用条件读取文本

时间:2018-07-25 10:15:45

标签: excel vba filesystemobject

我遇到问题,需要您的帮助。这是问题所在。我的文件夹中有一些excel文件,我必须自动打开这些文件才能进行某些操作。这些文件具有相同的名称,除了这样的文件编号:

文件夹名称:Extraction_Files 文件名:-“ System_Extraction_Supplier_1”                  -“ System_Extraction_Supplier_2”                  -“ System_Extraction_Supplier_3”

文件数可以更改,因此我使用了一个循环Do While来计算文件数,然后计划使用一个循环,将I = 1转换为(文件数)以打开所有主题。

请阅读我的代码。我知道我使用了错误的方式使用循环来读取文件名,但我共享了它,因为我没有其他想法。

这是我的代码:

Sub OpenFiles ()

    Dim MainPath as String 
    Dim CommonPath as String 
    Dim Count As Integer
    Dim i As Integer

   ' the main path is " C:\Desktop\Extraction_Files\System_Extraction_Supplier_i"
   'with i = 1 to Count ( file number )


    CommonPath = "C:\Desktop\Extraction_Files\System_Extraction_Supplier_*"

   'counting automatically the file number

    Filename = Dir ( CommonPath )

    Do While Filename <> "" 

       Count = Count + 1 
       Filename = Dir ()

    Loop

'the issue is below because this code generate a MsgBox showing a MainPath with the index i like this
'"C:\Desktop\Extraction_Files\System_Extraction_Supplier_i" 
' so vba can not find the files

    For i = 1 To count 

      MainPath = "C:\Desktop\Extraction_Files\System_Extraction_Supplier_" & "i" 
      MsgBox  MainPath  & 
      Workbooks.Open MainPath 

    Next 

End Sub 

什么是最好的方法?

2 个答案:

答案 0 :(得分:1)

如果要打开以“ NewFile_”开头的特定文件夹中的所有文件夹,则仅需要一个循环:

Sub OpenFolders()

    Dim path As String: path = ""C:\Desktop\Extraction_Files\""
    Dim fileStart As String: fileStart = "System_Extraction_Supplier_"
    Dim Fso As Object
    Dim objFolder As Object

    Set Fso = CreateObject("Scripting.FileSystemObject")
    Set objFolder = Fso.GetFolder(path)

    For Each objSubFolder In objFolder.subfolders
        If InStr(1, objSubFolder.Name, fileStart) Then
            Shell "explorer.exe " & objSubFolder, vbNormalFocus
            Debug.Print objSubFolder.Name
        End If
    Next objSubFolder

End Sub

使用Shell "explorer.exe "命令打开中的文件夹。该代码将打开"C:\yourFile\"中每个文件夹的名称,其中包含NewFile_。此检查是通过If InStr(1, objSubFolder.Name, fileStart) Then完成的。

答案 1 :(得分:1)

为什么在打开它们时不计算在内。您已经在识别它们了,为什么不随手打开每个文件:

Sub OpenFiles()

    Dim Filename As String
    Dim CommonPath As String
    Dim Count As Integer

    CommonPath = "C:\Desktop\Extraction_Files\"

    Filename = Dir(CommonPath & "System_Extraction_Supplier_*")

    Do While Filename <> ""

        MsgBox Filename
        Workbooks.Open CommonPath & Filename
        Count = Count + 1
        Filename = Dir()

    Loop

End Sub

PS。可能值得在搜索模式的末尾添加.xl*或类似内容来防止Excel尝试打开非Excel文件的文件:

Filename = Dir(CommonPath & "System_Extraction_Supplier_*.xl*")
相关问题