gpt4 book ai didi

excel - 根据单元格值检索文件路径(将单元格值与目录中的文件名匹配)

转载 作者:行者123 更新时间:2023-12-04 22:11:53 26 4
gpt4 key购买 nike

我一直在研究这个并将继续这样做,但我想在此过程中寻求一些帮助。
我正在尝试查找与 A1 的单元格内容匹配的文件是否存在于目录中。文件名可能在我要搜索的值之前或之后有字符。
下图显示了 A 列中的序列号,我试图查找具有该序列号的文件名是否存在于目录中,如果存在,则在 B 列中输出文件路径。
enter image description here enter image description here
理想情况下,结果将是这样。
enter image description here
我做了一些研究并遇到了类似的东西,这将告诉你它在一个目录中找到了多少个文件名与单元格匹配的文件,但是,我想调整它以提供文件路径(如果存在)。

    Sub countFiles()

Set last = Range("A:A").Find("*", Cells(1, 1), searchdirection:=xlPrevious)

For n = 2 To last.Row
Cells(n, 2).Value = loopThroughFilesCount("C:\Users\yalinbah\Desktop\boyner\gör‌​‌​seller2\Tekstil\", Cells(n, 1).Value)
Next

End Sub

Function loopThroughFilesCount(dirFolder As String, strToFind As String) As Double

Dim filePath As Variant
filePath = Dir(dirFolder)
While (filePath <> "")
If InStr(filePath, strToFind) > 0 Then
filesCount = filesCount + 1
End If
filePath = Dir
Wend

loopThroughFilesCount = filesCount

End Function
来源: Code from above

最佳答案

请尝试下一个功能:

Function GetFilePath(dirFolder As String, strToFind As String) As String
GetFilePath = Dir(dirFolder & "*" & strToFind & "*.*")
End Function
可以使用下一种方式进行测试:
Sub countFiles()
Dim sh As Worksheet, lastRow As Long, i As Long
Const foldPath As String = "C:\Users\yalinbah\Desktop\boyner\gör‌​‌​seller2\Tekstil\"
Set sh = ActiveSheet
lastRow = sh.Range("A" & sh.rows.count).End(xlUp).row
For i = 2 To lastRow
sh.Range("B" & i).value = foldPath & GetFilePath(foldPath, sh.Range("A" & i).value)
Next
End Sub
已编辑 :
下一个函数将返回包含部分字符串 ( strToFind) 的文件夹:
Function getFoldPath(dirFolder As String, strToFind As String) As String
Dim fldName As String
fldName = Dir(dirFolder & "*" & strToFind & "*", vbDirectory)
Do While fldName <> ""
If fldName <> "." And fldName <> ".." Then
' Use bitwise comparison to make sure dirFolder is a directory.
If (GetAttr(dirFolder & fldName) And vbDirectory) = vbDirectory Then
getFoldPath = fldName: Exit Function
End If
End If
fldName = Dir
Loop
End Function
您可以使用下一种方式对其进行测试。部分字符串应位于“C:C”列中:
Sub countFolders()
Dim sh As Worksheet, lastRow As Long, i As Long, fldName As String
Const foldPath As String = "C:\Users\yalinbah\Desktop\boyner\gör‌​‌​seller2\Tekstil\"
Set sh = ActiveSheet
lastRow = sh.Range("C" & sh.rows.count).End(xlUp).row
For i = 2 To lastRow
fldName = getFoldPath(foldPath, sh.Range("C" & i).value)
sh.Range("D" & i).value = IIf(fldName <> "", foldPath & getFoldPath(foldPath, sh.Range("C" & i).value), "")
Next
End Sub

关于excel - 根据单元格值检索文件路径(将单元格值与目录中的文件名匹配),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72190715/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com