我有一个关于一些VBA编码的问题。我有一个Excel电子表格,其中每个行都包含一个标识号(例如ABC0123456ABC)。我还有一个带有子文件夹的文件夹,其名称类似于Excel文件中的标识号。但是,其中一些子文件夹包含更多的文件(所有pdfs)。我想知道哪些文件夹包含文件(哪些不包含)。
因此,我想搜索所有包含文件的文件夹,这些文件夹的名称都是从excel文件中提取的。
我该怎么做呢?
发布于 2018-11-23 11:17:50
我认为你可以根据你的需要修改它;
如果我有这样的电子表格(数据范围B1:B3);

其中的每一行代表一个子文件夹,并且您想知道在每个子文件夹中是否有一个文件。
然后你可以使用这段代码。它将写入是否有一个文件的名称与B列到C列中显示的名称相同。
Public Sub FindFiles()
Dim myParentFolderLoc As String
Dim curValue As String
Dim myCell As Range
Dim myRange As Range
Dim outputRange As Range
' Change these to your range/Folder Location;
Set myRange = Sheet1.Range("B1:B3")
Set outputRange = Sheet1.Range("B1:C3") ' note the inclusion of the column to which i am writing
myParentFolderLoc = "C:\Example Folder\"
' Loop through your excel cells
For Each myCell In myRange.Cells
If isFileInFolder(myParentFolderLoc, myCell.Value) Then
myCell.Offset(0, 1).Value = "Files Exists"
Else
myCell.Offset(0, 1).Value = "No Files Exists"
End If
Next myCell
' Export to Txt
ExportRangeToTxt outputRange
End Sub
' Loop through the folder and see if a file contains the string
Private Function isFileInFolder(folderLocation As String, folderName As String) As Boolean
Dim i As Integer
i = 0
file = Dir(folderLocation & folderName & "\")
While (file <> "")
i = i + 1
file = Dir
Wend
If i > 0 Then
isFileInFolder = True
Else
isFileInFolder = False
End If
End Function
Private Sub ExportRangeToTxt(myRange As Range)
Dim myFile As String
Dim rng As Range
Dim cellValue As Variant
Dim i As Integer
Dim j As Integer
myFile = Application.DefaultFilePath & "\output.txt"
Set rng = myRange
Open myFile For Output As #1
For i = 1 To rng.Rows.Count
For j = 1 To rng.Columns.Count
cellValue = rng.Cells(i, j).Value
If j = rng.Columns.Count Then
Write #1, cellValue
Else
Write #1, cellValue,
End If
Next j
Next i
Close #1
MsgBox "Text Export Complete - Check the file at: " & myFile
End Sub这将导出一个文件到应用程序的默认文件路径--消息框将告诉您它在哪里。
记住要更新范围,如示例所示,以包括所有的子文件夹。我可以自动做到这一点,但我不想做任何假设,因为没有看到你的数据。
https://stackoverflow.com/questions/53443778
复制相似问题