Excel VBA 文件名搜索返回完整路径


Sub Sample()
Dim sh As Worksheet
Dim rng As Range
Dim i As Long, Lrow As Long
Dim fPath As String, sPath As String
With Application.FileDialog(msoFileDialogFolderPicker)
.Show
fPath = .SelectedItems(1)
End With
If Right(fPath, 1) <> "" Then
fPath = fPath & ""
End If
Set sh = ThisWorkbook.Sheets("Sheet1")
With sh
Lrow = .Range("A" & .Rows.Count).End(xlUp).Row
For i = 2 To Lrow
'~~> Check for partial match
sPath = fPath & "*" & .Range("A" & i).Value & "*.*"
If Len(Trim(Dir(sPath))) > 0 Then
.Range("B" & i).Value = Dir(sPath)
End If
Next i
End With

嗨,我在上面使用此代码在与工作表中的单元格匹配时返回文件名。我想知道如何返回完整的路径名而不仅仅是文件名?我需要对此代码进行哪些更改?

你已经有fPath了; 只需连接:

.Range("B" & i).Value = fpath & Dir(sPath)

最新更新