我找到了这个论坛的代码。我已经非常努力地取得了成果,但在这部分失败了。设置f = fs.GetFile(fwb)。运行时错误' 53'我正致力于Win 7,Office 2013。
我有一个Excel电子表格,其中包含A列中的文件名.A列中列出的文件名出现在一个或多个源目录中的一个或多个Ms office .doc文件中。
我需要Excel以递归方式搜索.doc文件,并将包含A列中指定的文件名的文件的路径返回到B列。如果有多个文件转到C列等。< / p>
我迫切需要这个宏。请有人帮助我。
__________________________________ __|______A_____|______B_____|_____ 1 | test_1.doc |c:\cost\test_1.doc| 2 | test_2.doc |c:\cost\test_2.doc|
Private Sub CommandButton1_Click()
Dim sh As Worksheet, rng As Range, lr As Long, fPath As String
Set sh = Sheets(1) 'Change to actual
lstRw = sh.Cells.Find(
What:="*",
After:=sh.Range("A1"),
LookAt:=xlPart,
LookIn:=xlFormulas,
SearchOrder:=xlByRows,
SearchDirection:=xlPrevious,
MatchCase:=False
).Row
Set rng = sh.Range("A2:A" & lstRw)
With Application.FileDialog(msoFileDialogFolderPicker)
.Show
fPath = .SelectedItems(1)
End With
If Right(fPath, 1) <> "\" Then
fPath = fPath & "\"
End If
fwb = Dir(fPath & "*.*")
x = 2
Do While fwb <> ""
For Each c In rng
If InStr(LCase(fwb), LCase(c.Value)) > 0 Then
Worksheets("Sheet2").Range("C" & x) = fwb
Set fs = CreateObject("Scripting.FileSystemObject")
Set f = fs.GetFile(fwb) 'Run time error '53'
Worksheets("Sheet2").Range("D" & x) = f.DateLastModified
Worksheets("Sheet2").Range("B" & x) = f.Path
Worksheets("sheet2").Range("A" & x) = c.Value
Columns("A:D").AutoFit
Set fs = Nothing
Set f = Nothing
x = x + 1
End If
Next
fwb = Dir
Loop
Set sh = Nothing
Set rng = Nothing
Sheets(2).Activate
End Sub
答案 0 :(得分:0)
fwb = Dir(fPath & "*.*")
...
Set f = fs.GetFile(fwb) 'Run time error '53'
Dir(...)函数只返回文件名(例如“myfile.doc”),因此在调用GetFile(...)时必须在其前面添加目录路径:
Set f = fs.GetFile(fPath & fwb)