我有两个文件夹,其中包含类似名称的excel文件,但模板不同。模板之一(较新)为空白,而旧模板包含所有数据。
模板A和模板B之间的模式是一致的-我知道A中的哪个单元转到B中的哪个单元,但是我不确定如何在VBA中创建宏以一次有效地处理所有文件
到目前为止,我已经创建了两个文件系统对象,每个文件夹一个-但是我不确定如何从另一个文件夹中提取相同的文件以开始克隆过程。
为避免excel在打开同名文件时出现问题,较新的模板的末尾带有3个字符的后缀。
任何建议将不胜感激!
Set picker = Application.FileDialog(msoFileDialogFolderPicker)
picker.Show
Set fldrs = picker.SelectedItems
fpath1 = fldrs(1)
Set picker = Application.FileDialog(msoFileDialogFolderPicker)
picker.Show
Set fldrs = picker.SelectedItems
fpath2 = fldrs(1)
Dim fso1 As Object
Dim vfolder1 As Object
Dim fso2 As Object
Dim vfolder2 As Object
Set fso1 = CreateObject("Scripting.FileSystemObject")
Set vfolder1 = fso1.GetFolder(fpath1)
Set fso2 = CreateObject("scripting.filesystemobject")
Set vfolder2 = fso2.GetFolder(fpath2)
For Each vfile In vfolder1.Files
答案 0 :(得分:0)
假设文件名总是开始相同(“较新的模板的后缀为 ”是3个字符),只需使用GetBaseName
从文件名中删除路径和扩展名,然后将它们进行比较,以查看目标文件名是否以源文件名开头:
With New Scripting.FileSystemObject
Dim source As Folder, target As Folder
Set source = .GetFolder(fpath1)
Set target = .GetFolder(fpath2)
Dim item As File, fileName As String
For Each item In source.Files
'Get the filename without path or extension.
fileName = .GetBaseName(item)
Dim searched As File
For Each searched In target
'Does the file start with fileName?
If InStr(1, .GetBaseName(item), fileName) = 1 Then
'Files match, do your thing here.
End If
Next
Next
End With
请注意,这是早期绑定。如果您坚持不添加对Microsoft脚本运行时的引用(几乎从来没有理由不这样做),只需将早期绑定变量更改为Object
并将New Scripting.FileSystemObject
替换为CreateObject