VB 代码使用 DOS 命令 dir 获取 E:\ 所有文件详细列表到表格
以下是使用 VB 代码获取 E:\ 所有文件详细列表并输出到表格的示例:
Sub Main()
Dim objShell As Object
Dim objCmd As Object
Dim objOutput As Object
Dim strResult As String
Dim arrLines() As String
Dim i As Integer
Dim filePath As String
Dim excelApp As Object
Dim excelWorkbook As Object
Dim excelWorksheet As Object
' 创建 Shell 对象
Set objShell = CreateObject("WScript.Shell")
' 创建 Cmd 对象
Set objCmd = objShell.Exec("cmd /c dir E:\ /s /b /A:-D")
' 获取 Cmd 输出结果
Set objOutput = objCmd.StdOut
' 读取输出结果并存储到字符串
strResult = objOutput.ReadAll
' 将字符串按换行符分割为数组
arrLines = Split(strResult, vbCrLf)
' 创建 Excel 应用程序对象
Set excelApp = CreateObject("Excel.Application")
' 创建新的工作簿
Set excelWorkbook = excelApp.Workbooks.Add
' 获取第一个工作表
Set excelWorksheet = excelWorkbook.Worksheets(1)
' 在表格中添加标题
excelWorksheet.Cells(1, 1).Value = "文件路径"
' 循环遍历文件路径数组
For i = 0 To UBound(arrLines)
' 获取文件路径
filePath = arrLines(i)
' 在表格中添加文件路径
excelWorksheet.Cells(i + 2, 1).Value = filePath
Next i
' 保存 Excel 文件
excelWorkbook.SaveAs "E:\文件列表.xlsx"
' 关闭 Excel 应用程序
excelApp.Quit
' 释放对象
Set excelWorksheet = Nothing
Set excelWorkbook = Nothing
Set excelApp = Nothing
Set objOutput = Nothing
Set objCmd = Nothing
Set objShell = Nothing
End Sub
Main
此代码使用 WScript.Shell 对象执行 dir 命令获取 E:\ 目录下的所有文件的详细列表,并将结果存储到字符串中。然后,通过创建 Excel.Application 对象,创建新的工作簿,并将文件路径写入表格。最后,保存 Excel 文件并关闭应用程序。
原文地址: https://www.cveoy.top/t/topic/qb5p 著作权归作者所有。请勿转载和采集!