gpt4 book ai didi

vba - VBA 中的文件搜索

转载 作者:行者123 更新时间:2023-12-02 12:02:42 25 4
gpt4 key购买 nike

我编写了一个 vba 代码来浏览所有路径文件夹并搜索“strings.xml”文件。

Dim oFS As Office.FileSearch
Dim i As Integer
Set oFS = Application.FileSearch

With oFS
.NewSearch
.FileType = msoFileTypeAllFiles
.Filename = "strings.xml"
.LookIn = "D:\Workspace"
.SearchSubFolders = True
.Execute

MsgBox "Finish ! " & .FoundFiles.Count & " item found !"
End With

但是,在我的工作区中,我有许多当前代码所在的“strings.xml”文件,但我只想在特定的子文件夹中找到“strings.xml”;例如./values/strings.xml 文件。

最佳答案

以下内容将在您的根工作文件夹下递归查找 Values\Strings.xml 匹配项,并将它们列在 Scripting.Dictionary 中。对象。

主要文件/文件夹搜索是通过简单的 Dir function 执行的.

Sub dir_ValuesStringsXML_list()
Dim f As Long, ff As String, fp As String, fn As String, tmp As String
Dim vfn As Variant, dFILEs As Object 'New scripting_dictionary

Set dFILEs = CreateObject("Scripting.Dictionary")
dFILEs.CompareMode = vbTextCompare

'set vars for c:\temp\Workspace\*\Values\Strings.xml
fp = Environ("TMP") & Chr(92) & "Workspace"
ff = "Values"
fn = "Strings.xml"
dFILEs.Item(fp) = 0

'get folder list
Do
f = dFILEs.Count
For Each vfn In dFILEs
If Not CBool(dFILEs.Item(vfn)) Then

tmp = Dir(vfn & Chr(92) & Chr(42), vbDirectory)
Do While CBool(Len(tmp))
If Not CBool(InStr(1, tmp, Chr(46))) Then
dFILEs.Item(vfn & Chr(92) & tmp) = 0
End If
tmp = Dir
Loop
'Debug.Print dFILEs.Count
dFILEs.Item(vfn) = 1
End If
Next vfn
Loop Until f = dFILEs.Count

'remove the folders and check for Values\Strings.xml
For Each vfn In dFILEs
If CBool(dFILEs.Item(vfn)) Then
If LCase(Split(vfn, Chr(92))(UBound(Split(vfn, Chr(92))))) = LCase(ff) And _
CBool(Len(Dir(vfn & Chr(92) & fn, vbReadOnly + vbHidden + vbSystem))) Then
dFILEs.Item(vfn & Chr(92) & fn) = 0
End If
dFILEs.Remove vfn
End If
Next vfn

'list the files
For Each vfn In dFILEs
Debug.Print "from dict: " & vfn
Next vfn

dFILEs.RemoveAll: Set dFILEs = Nothing

End Sub
<小时/>

如果您希望将 Scripting.Dictionary 的后期绑定(bind)转换为早期绑定(bind),则必须添加 Microsoft Scripting Runtime VBE 工具►引用。

关于vba - VBA 中的文件搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15339006/

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