使用Excel VBA查找特定的文件夹

我一直在努力将工作簿分发给其他人,并且大部分代码依赖于从保存在共享同步文件夹中的工作簿拉取 – 我们称之为“牙齿”。

对于我来说,TEETH被安装到这个path: "C:\Users\TEETH"但是对于其他一些,它安装了"C:\Users\desktop\TEETH""C:\Users\My Documents\TEETH"

我在考虑两种解决scheme1.一种方式,Excel可以通过C:\目录相对快速地查看,find文件夹,然后在单元格中输出它的path2.让用户find文件夹,然后将path转储到细胞

以上两种方式是可能的吗? 或者,还有更好的方法?

谢谢!

search整个驱动​​器将非常耗时。 我创buildgetFileListrecursionsearch所有文件夹和子文件夹返回数组中的文件path。 当它find正确的目录时,可以通过让函数退出来加速进程。

我build议使用SaveSetting将path保存到registry中,然后使用GetAllSettings进行后续操作

HowTo_GetFileListmacros向您显示如何过滤文件path的数组。

在这里输入图像说明

 Sub HowTo_GetFileList() Const MATCHVALUE As String = "Demo" Dim f, FileList, FilteredList FileList = getFileList("C:\Users\Owner\Downloads") FilteredList = Filter(FileList, MATCHVALUE) For Each f In FilteredList 'Do Something Next End Sub Function getFileList(localRoot As String, Optional fld, Optional ftpArray) Dim fso, f, baseFolder, subFolder, ftpFile, i Set fso = CreateObject("Scripting.Filesystemobject") If IsMissing(fld) Then Set baseFolder = fso.GetFolder(localRoot) Else Set baseFolder = fld End If For Each f In baseFolder.Files If IsMissing(ftpArray) Then ReDim ftpArray(0) Else i = UBound(ftpArray) + 1 ReDim Preserve ftpArray(i) End If ftpArray(i) = f.Path Next For Each subFolder In baseFolder.SubFolders getFileList localRoot, subFolder, ftpArray Next getFileList = ftpArray End Function 

最有效的select是使LDAP查询返回共享文件夹列表。 VBSEditor.com的这个示例脚本就可以做到这一点。 这将需要对Active Directory有相当的了解。

这不是更复杂的答案,只是一个打开文件夹select框并返回一个string与选定的path的函数。 我把它放在我的大部分应用程序中,每次要运行代码时都要select一个文件夹不是很费时间,而且非常稳定。

 Public Function FolderSelection() As String Dim objFD As Object Dim strOut As String strOut = vbNullString Set objFD = Application.FileDialog(4) objFD.Title = 'the title you want to show objFD.InitialFileName = 'standard path If objFD.Show = -1 Then strOut = objFD.SelectedItems(1) End If Set objFD = Nothing FolderSelection = strOut End Function