【问题标题】:Search for a file and return path搜索文件并返回路径
【发布时间】:2020-06-22 05:58:59
【问题描述】:

我需要一些想法...我有一个包含文件名的列。我有一个包含所有 excel 文件的文件夹。是否可以链接这两者并获取相邻单元格中的文件路径?

例如:我在 A1、A2 列中有一个值“AAA”、“BBB”等>

我每次都会手动选择宏的文件夹路径。

最后,通过比较A列中的单元格值和文件夹中的文件名,匹配项的文件路径应该显示在B列中。

【问题讨论】:

  • 需要更多细节。示例屏幕截图也很有用。另外,您自己尝试过什么来完成这项任务?
  • 您要执行搜索吗?因为否则 Excel 应该知道在哪里查找。它可以是调用文件的父文件夹,也可以是您自己提供的某个预定义文件夹。
  • 是的,我想在文件夹中搜索单元格值并获取文件的路径

标签: excel vba search directory path


【解决方案1】:

在您最后一次编辑之后,这应该可以工作:

Sub SetFullPath()

MyPath = "C:\Insert path of the folder where you have the files here\"
For Each cell In Range("B1:B100")'Customize your range
If Len(Dir(MyPath & Range("A" & cell.Row).Value & ".xlsx")) = 0 Then
cell.Value = "File Not Found"
Else: cell.Value = MyPath & Range("A" & cell.Row).Value & ".xlsx"
End If
Next

End Sub

如果需要更改,请告诉我。

【讨论】:

  • 嗨,我需要通过浏览器来选择路径。而且当路径被输入时,这段代码对我不起作用。
  • 嗯,那么我不确定您所说的“我每次都会手动选择宏的文件夹路径”是什么意思。你得到什么样的错误?我做了一个快速测试,效果很好。
【解决方案2】:

这个子 (return_paths) 应该这样做。它使用函数GivePath。

Sub return_paths()
  Dim sSearchPath As String: sSearchPath = "C:\Temp"
  Dim oFSO As Object
  Dim i As Long
  Set oFSO = CreateObject("Scripting.FileSystemObject")
  For i = 1 To ActiveSheet.Cells(ActiveSheet.Rows.Count, 1).End(xlUp).Row
    ActiveSheet.Cells(i, 2) = GivePath(ActiveSheet.Cells(i, 1), oFSO.GetFolder(sSearchPath))
  Next
End Sub


Private Function GivePath(sName As String, oDir As Object, Optional ByRef blnFound As Boolean) As String
  Dim f As Object
  Dim sf As Object

  If blnFound Then Exit Function

  For Each f In oDir.Files
    If f.Name = sName Then
      GivePath = f.Path
      blnFound = True
    End If
    If blnFound Then Exit Function
  Next

  For Each sf In oDir.SubFolders
    GivePath = GivePath(sName, sf, blnFound)
    If blnFound Then Exit Function
  Next

  If GivePath = "" Then GivePath = "The file was not found"

End Function

运行后结果如下:

【讨论】:

    【解决方案3】:

    请找到我从合并所有结果中得到的解决方案。多谢你们。你们都太棒了!!!

    Sub FolderDetails()
    Dim FSO As New FileSystemObject
    Set FSO = CreateObject("Scripting.FileSystemObject")
    Dim rRng As Range, rCl As Range
    Dim sFolder As String
    ''// Open the select folder prompt
    With Application.FileDialog(msoFileDialogFolderPicker)
    If .Show = -1 Then ' if OK is pressed
    sFolder = .SelectedItems(1)
    End If
    End With
    Set rRng = Range(Cells(1, 1), Cells(Rows.Count, 1).End(xlUp))
    For Each rCl In rRng
    If FSO.FileExists(sFolder & Application.PathSeparator & rCl.Value & ".xlsx") Then
    rCl.Offset(, 1).Value = sFolder
    Else: rCl.Offset(, 1).Value = "The File Does Not Exist"
    End If
    Next rCl
    End Sub
    

    【讨论】:

      猜你喜欢
      • 2015-10-03
      • 1970-01-01
      • 2015-08-15
      • 2021-02-11
      • 1970-01-01
      • 2018-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多