首页 > 解决方案 > 如何使用条件读取文本 if

问题描述

我有一个问题,我需要你的帮助。这就是问题所在。我在一个文件夹中有一些 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 

最好的方法是什么?

标签: excelvbafilesystemobject

解决方案


如果要打开以“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.


推荐阅读