如何使用条件 if 阅读文本

how to read a text using condition if

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

文件夹名称:Extraction_Files 文件名:- "System_Extraction_Supplier_1" - "System_Extraction_Supplier_2" - "System_Extraction_Supplier_3"

文件的数量可以改变,所以我使用循环 Do While 来计算文件的数量,然后计划是使用循环 I =1 to ( number of files) 打开所有主题。

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

这是我的代码:

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 

最好的方法是什么?

如果要打开特定文件夹中所有以"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.

完成的

为什么不在打开时计数。您已经识别了它们,所以为什么不边走边打开每个文件:

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*")