我一直试图为VBA编写代码,在给定用户输入的文件夹路径的情况下循环浏览文件夹,并粘贴一些信息,如一系列单元格,以及基于我工作簿的文件名关于文件名是否包含特定字符串。
目前我有一个代码,它将在Excel中的单元格1,1中输入文件夹路径,但它将返回所有文件名,而不仅仅是包含" abc"的文件名。例如。自从我使用VBA以来已经有一段时间了,这是我回归它的方式。
Sub getFile()
Dim MyFolder As String
Dim file As String
MyFolder = Cells(1, 1)
file = Dir(MyFolder & ".xl??")
Dim col As Integer
col = 2
Do While file <> ""
Cells(3, col) = file
col = col + 1
file = Dir()
Loop
End Sub
我的问题是,我还没有找到一种方法来合并一个&#34; If&#34;说只使用包含字符串&#34; abc&#34;
的文件谢谢大家!
答案 0 :(得分:1)
尝试使用
file = Dir(MyFolder & "*abc*.xl??")
而不是
file = Dir(MyFolder & ".xl??")
只是为了关闭这篇文章,为了不再有另一个未解决的问题(答案在评论中)我在这里重新发表我的评论作为解决方案。
答案 1 :(得分:0)
我认为你没有说清楚,但我相信你想在他们的名字中循环包含“abc”的文件,这是正确的吗?
如果是这样,在声明变量“file”时在Dir函数中使用星号,如下所示:
file = Dir(MyFolder & "*abc*.xl*")
答案 2 :(得分:0)
如果您只是稍微修改一下代码,这里有一个很棒的样本可以完成您想要的所有内容以及更多内容....
http://www.learnexcelmacro.com/wp/2011/11/how-to-get-list-of-all-files-in-a-folder-and-sub-folders/
从名为&#39;立即下载&#39;。
的链接下载示例文件Sub GetFilesInFolder(SourceFolderName As String)
'--- For Example:Folder Name= "D:\Folder Name\"
Dim FSO As Scripting.FileSystemObject
Dim SourceFolder As Scripting.folder, SubFolder As Scripting.folder
Dim FileItem As Scripting.File
Set FSO = New Scripting.FileSystemObject
Set SourceFolder = FSO.GetFolder(SourceFolderName)
'--- This is for displaying, whereever you want can be configured
r = 14
For Each FileItem In SourceFolder.Files
Cells(r, 2).Formula = r - 13
Cells(r, 3).Formula = FileItem.Name
Cells(r, 4).Formula = FileItem.Path
Cells(r, 5).Formula = FileItem.Size
Cells(r, 6).Formula = FileItem.Type
Cells(r, 7).Formula = FileItem.DateLastModified
Cells(r, 8).Formula = "=HYPERLINK(""" & FileItem.Path & """,""" & "Click Here to Open" & """)"
r = r + 1 ' next row number
Next FileItem
Set FileItem = Nothing
Set SourceFolder = Nothing
Set FSO = Nothing
End Sub
Sub GetFilesInFolder(SourceFolderName As String, Subfolders As Boolean)
'--- For Example:Folder Name= "D:\Folder Name\" and Flag as Yes or No
Dim FSO As Scripting.FileSystemObject
Dim SourceFolder As Scripting.folder, SubFolder As Scripting.folder
Dim FileItem As Scripting.File
'Dim r As Long
Set FSO = New Scripting.FileSystemObject
Set SourceFolder = FSO.GetFolder(SourceFolderName)
'--- This is for displaying, whereever you want can be configured
r = 14
For Each FileItem In SourceFolder.Files
Cells(r, 2).Formula = r - 13
Cells(r, 3).Formula = FileItem.Name
Cells(r, 4).Formula = FileItem.Path
Cells(r, 5).Formula = FileItem.Size
Cells(r, 6).Formula = FileItem.Type
Cells(r, 7).Formula = FileItem.DateLastModified
Cells(r, 8).Formula = "=HYPERLINK(""" & FileItem.Path & """,""" & "Click Here to Open" & """)"
r = r + 1 ' next row number
Next FileItem
'--- This is the Function to go each and Every Folder and get the Files. This is a Nested-Function Calling.
If Subfolders = True Then
For Each SubFolder In SourceFolder.Subfolders
ListFilesInFolder SubFolder.Path, True
Next SubFolder
End If
Set FileItem = Nothing
Set SourceFolder = Nothing
Set FSO = Nothing
End Sub