將VBA與Microsoft Scripting Runtime的引用結合使用。我試圖比較兩個不同目錄中的文件名,以查找兩個目錄中是否存在相同的文件。但是,我並不是在尋找完全匹配;我想剝離某些類型的前綴,因此,例如,A-12234.pdf
,12234.pdf
和A_ 12234.pdf
應被視爲彼此相等。比較使用VBA的FileSystemObject獲取的文件名的修改版本
比方說,我有一個函數stripPrefix()
執行必要的字符串操作來更改文件轉換成可以與他人進行比較的版本 - 在現有情況下,stripPrefix()
將返回12234.pdf
所有3.然後,我可以比較文件名在目錄c:\dir1
和c:\dir2
使用下面的代碼:
sub findMatchFilenames()
dim fso as fileSystemObject
dim dir1 as folder
dim dir2 as folder
dim file1 as file
dim file2 as file
set fso=new fileSystemObject
set dir1=fso.getfolder("c:\dir1")
set dir2=fso.getfolder("c:\dir2")
for each file1 in dir1.files
for each file2 in dir2.files
if stripPrefix(file1.name)=stripPrefix(file2.name) then
debug.print file1.name & " matches " & file2.name
end if
next file2
next file1
end sub
大問題就在這裏:我每次迭代for..next file1
循環時間我打電話stripPrefix()
爲相同的文件名中dir2
。我可以構建每個文件名的已刪除版本的數組dir1Array
和dir2Array
,但似乎我無法將它們與dir1
和dir2
中的Files
收藏相關聯,因爲Files
收藏沒有數字索引。我知道,因爲我嘗試使用:
Set fso = New FileSystemObject
Set folderObj = fso.GetFolder("c:\data")
fileCount = folderObj.Files.Count
For c = 1 To fileCount
MsgBox c & " " & folderObj.Files(c).name
Next
和folderObj.Files(c).name
得到了一個「無效的過程調用或參數」。我想,當我走在for..next
循環和使用計數器來指回陣列,就像我可以增加一個計數器:
'after creating arrays of stripPrefix() for dir1 and dir2
ctr1=0
for each file1 in dir1.files
ctr2=0
for each file2 in dir2.files
if dir1array(ctr1)=dir2array(ctr2) then
debug.print file1.name & " matches " & file2.name
end if
ctr2=ctr2+1
next file2
ctr1=ctr1+1
next file1
,但似乎真的沉悶。有沒有更好的方法來處理這個文件名比較操作?
我覺得這種笨拙是來自使用VBA的恐懼。如果你可以(或者可以)向Python或類似的shell發表意見,那將會容易得多。 – Vicky
@Vicky,不幸的是,這是一個宏,我將不得不分發給其他可能沒有安裝Python的用戶。我在VBA之外調用的任何東西都需要成爲標準XP/Win7發行版的一部分。 – sigil
這個問題有很多東西。我爲了一個人無法把頭圍住它。你到底在問什麼?你可能想考慮讓你的問題更加簡潔,關注你的主要觀點。這樣的問題可能會吸引更多的幫助。 –