VBA求助,新人学习遇到困难
需求如下:需要批量处理EXCEL文件,文件存放在文件夹和子文件夹,需要对这个文件夹和子文件夹的文件都逐个打开处理操作,学习了一天遍历文件夹……还是没学懂……求助……
代码如下,有帮助麻烦点个采纳【本回答右上角】,谢谢~~
Sub Enlist_Directories(strPath As String, lngSheet As Long, index As Long)
Dim strFldrList() As String
Dim lngArrayMax, x As Long
lngArrayMax = 0
Dim strFn As Variant
strFn = Dir(strPath & "*.*", 23)
While strFn <> ""
If strFn <> "." And strFn <> ".." Then
If (GetAttr(strPath & strFn) And vbDirectory) = vbDirectory Then
lngArrayMax = lngArrayMax + 1
ReDim Preserve strFldrList(lngArrayMax)
strFldrList(lngArrayMax) = strPath & strFn & "\"
Else
If strFn Like "*.xls*" Then ''''''''''''查找函数.xls后缀的文件
Worksheets(lngSheet).Cells(index, 1) = strPath & strFn
index = index + 1
End If
End If
End If
strFn = Dir()
Wend
If lngArrayMax <> 0 Then
For x = 1 To lngArrayMax
Call Enlist_Directories(strFldrList(x), lngSheet, index)
Next
End If
End Sub
Sub test()
Dim strPath As String
Dim lngSheet As Long
strPath = Application.InputBox("Input the path:", "Path", ActiveWorkbook.Path & "\", , , , , 2)
If Right(strPath, 1) <> "\" Then strPath = strPath & "\"'格式化路径,目录需要\结尾
lngSheet = 1 '写入的sheet下标
Call Enlist_Directories(strPath, lngSheet, 2)
End Sub