简体   繁体   English

如何在VBA中打开具有特定名称的文件夹中的文件?

[英]How to open files in folder with specific name in VBA?

I'm trying to open files in a folder with VBA under the condition that their names are similar to the names of other files, which in turn will also be opened. 我正在尝试使用VBA打开文件夹中的文件,条件是它们的名称与其他文件的名称相似,而其他文件的名称也将被打开。

With the following code I'm opening files with names "1_FirmA", "1_FrimB",.... from folder1 and afterwards I'm executing some commands on those files. 使用以下代码,我从folder1打开名称为“ 1_FirmA”,“ 1_FrimB”,...的文件,然后在这些文件上执行一些命令。

My problem is that I want to open files from folder2 whenever their names are similar to the name of the file from folder1 that is openend in the loop. 我的问题是,每当文件名与循环中openend的folder1中的文件名相似时,我都想从folder2中打开文件。 The names of the files in folder2 are "2_FirmA", "2_FirmB",... . folder2中文件的名称为“ 2_FirmA”,“ 2_FirmB”,...。 So when I open "1_FirmA" from folder1 I want to open "2_FirmA" from folder2. 因此,当我从文件夹1打开“ 1_FirmA”时,我想从文件夹2打开“ 2_FirmA”。 Does anybody have an idea how I could achieve this? 有人知道我该如何实现吗?

Best regards 最好的祝福

Sub MySub()
Dim y As Workbook
Dim z As Workbook
Set fso = CreateOnject("Scripting.FileSystemObject")
Set fldr = fso.GetFolder("path\folder1\")
Set fldr2 = fso.GetFolder("path\folder2\")

For Each yFile in fldr.Files
If fso.GetExtensionName(yFile.Name) = "xlsx" then
Set y = Workbooks.Open(yFile.Path)

'Stuff I want to do with workbook y

End if
Next

End Sub()


Will this work: 这项工作会:

Sub MySub()
Dim y As Workbook
Dim z As Workbook
Set FSO = CreateOnject("Scripting.FileSystemObject")
Set fldr = FSO.GetFolder("path\folder1\")
Set fldr2 = FSO.GetFolder("path\folder2\")

For Each yFile In fldr.Files
If FSO.GetExtensionName(yFile.Name) = "xlsx" Then
Set y = Workbooks.Open(yFile.path)
Set z = Workbooks.Open(fldr2 & "2" & Right(yFile.Name, Len(yFile.Name) - 1))


'Stuff I want to do with workbook y

' stuff you can do with z now

End If
Next

End Sub

Just manipulate the Name and open the Workbook from 2nd Folder, Given the Pattern is same as you mentioned. 只要操作名称并从第二个文件夹中打开工作簿,给定的模式与您提到的相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM