excel - 如何使用条件读取文本 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
最好的方法是什么?
解决方案
如果要打开以“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
vba中的文件夹使用Shell "explorer.exe "
命令打开。代码会打开 中的每个文件夹"C:\yourFile\"
,其中包含NewFile_
名称。这个检查是用 If InStr(1, objSubFolder.Name, fileStart) Then
.
推荐阅读
- python - 将 Keras CNN 模型(model.h5 或 model.json)集成到 C# 项目中
- javascript - 关于更新 Firestore 文档的值
- geogebra - GeoGebra 3D 中的旋转角度
- mysql - MySQL – 无法查看不同表中的数据,因为作业号有后缀
- r - 从环境创建对象,在循环中使用
- python - 如何在没有 PermissionError 的情况下向 selenium 添加 chrome 扩展:[Errno 13] Permission denied?
- php - sqlDataPovider 到 activeDataProvider Yii2
- angular - 在堆积图中选择一系列列并检索相关数据
- swift - 从开放天气 api SwiftUI 获取错误
- reactjs - 后端中的 Microsoft 身份验证和访问令牌验证?