查找包含文件(VBA)的文件夹

时间:2018-11-23 09:22:38

标签: excel vba find directory

我对某些VBA编码有疑问。我有一个Excel电子表格,其中的行各包含一个标识号(例如ABC0123456ABC)。我也有一个带有子文件夹的文件夹,该子文件夹的名称类似于Excel文件中的标识号。但是,其中一些子文件夹包含更多文件(所有pdf)。我想知道哪些文件夹包含文件(哪些不包含)。

因此,我想搜索所有包含名称都来自excel文件的文件的文件夹。

我该怎么做?

1 个答案:

答案 0 :(得分:0)

我认为您可以根据自己的需要进行修改;

如果我有这样的电子表格(数据在B1:B3范围内);

enter image description here

其中每一行代表一个子文件夹,并且您想知道每个子文件夹中是否都有文件

然后您可以使用此代码。它将写入是否包含与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

这会将文件导出到应用程序的默认文件路径-消息框将告诉您它在哪里。

请记住,如示例所示更新范围,以包括所有子文件夹。我可以自动执行此操作,但是我不想做任何未看到您的数据的假设。

相关问题