excel - Excel VBA FileSystemObject 获取文件夹
问题描述
我希望能够获取有关我输入一系列单元格的路径列表的文件信息。我也不想得到所有的子文件夹。我的这段代码使用 1 个文件夹路径效果很好。
Sub Get_Information()
Dim sh As Worksheet
Set sh = ThisWorkbook.Sheets("Sheet1")
Dim fso As New FileSystemObject
Dim fo As Folder
Dim f As File
Dim last_row As Integer
sh.Rows(1).Font.Size = 18
Set fo = fso.GetFolder(sh.Range("H1").Value)
For Each f In fo.Files
last_row = sh.Range("A" & Application.Rows.Count).End(xlUp).Row + 1
sh.Range("A" & last_row).Value = f.Name
sh.Range("B" & last_row).Value = f.Type
sh.Range("C" & last_row).Value = f.Size / 1024
sh.Range("D" & last_row).Value = f.DateLastModified
Next
MsgBox ("Done")
解决方案
如果您在一个单元格中有所有路径,则可以在该单元格中拆分字符串,然后使用数组循环
Sub Get_Information()
Dim sh As Worksheet
Set sh = ThisWorkbook.Sheets("Sheet1")
Dim fso As New FileSystemObject
Dim fo As Folder
Dim f As File
Dim pathArray as Variant
Dim SplitString as String
Dim last_row As Integer
sh.Rows(1).Font.Size = 18
SplitString = sh.Range("H1").Value
pathArray = Split(SplitString, ";") 'change to whatever seperator you are using
For each pth in pathArray
Set fo = fso.GetFolder(pth)
For Each f In fo.Files
last_row = sh.Range("A" & Application.Rows.Count).End(xlUp).Row + 1
sh.Range("A" & last_row).Value = f.Name
sh.Range("B" & last_row).Value = f.Type
sh.Range("C" & last_row).Value = f.Size / 1024
sh.Range("D" & last_row).Value = f.DateLastModified
Next f
Next pth
MsgBox ("Done")
编辑
如果您想循环遍历一系列单元格:
Sub Get_Information()
Dim sh As Worksheet
Set sh = ThisWorkbook.Sheets("Sheet1")
Dim fso As New FileSystemObject
Dim fo As Folder
Dim f As File
Dim c as Range
Dim last_row As Integer
sh.Rows(1).Font.Size = 18
For each pth in sh.Range("H1:H" & last_row) 'Edit range
If not pth.value = ""
Set fo = fso.GetFolder(c.Value)
For Each f In fo.Files
last_row = sh.Range("A" & Application.Rows.Count).End(xlUp).Row + 1
sh.Range("A" & last_row).Value = f.Name
sh.Range("B" & last_row).Value = f.Type
sh.Range("C" & last_row).Value = f.Size / 1024
sh.Range("D" & last_row).Value = f.DateLastModified
Next f
End If
Next pth
MsgBox ("Done")
推荐阅读
- python - 定义为另一个列表类型类属性的长度的类属性不会自行更新并且总是返回相同的值
- excel - 使用 Powerquery 从 Excel 缩进中提取层次结构
- python - 如何通过设置Excel单元格中的文本颜色?
- unity3d - 为什么统一跳过我的开始屏幕场景?
- c# - 如何在 Linux 上的 UriBuilder 中使用文件路径
- visual-studio-2013 - “无法找到包源 vsupdate_KB2829760”Visual Studio 2013 终极更新 5
- python - Django 管理员,在自定义视图中找不到页面
- c# - Azure 异常检测器与 C# 第 2 部分
- html - 将容器宽度扩展到适合内容之外
- javascript - vue-grid-layout 根据图片允许大小拖拽