我需要从平面文件中获取数据到电子表格中,以便对占用磁盘空间的项目进行趋势分析。
我的目标是导入每个服务器每月生成的驱动器文件夹大小数据。
每个文件都被命名为服务器名称和yy-MM日期标签。
我的原始数据工作表中有一个列,用于显示每个文件的数据。
我想将文件的内容导入每个列标题下方的行中,以及在找不到与列数据匹配的文件名时跳过导入。
例如,9月份的平面文件名为“服务器18-09”。它包含10行数字,如下所示。每行是定义的文件夹/路径的数据:
文件名:“ server1 18-09”
文件数据内容:
17.6689338684082
25932849152
5604237
763363328
0
884641998
13426067872
16316400460
1798912358
14219095504
我的电子表格如下所示:
答案 0 :(得分:0)
我将从调查FileSystemObject开始。在浏览计算机上的文件夹/文件时非常有帮助,并具有read files的功能。首先是这样的:
(代码未经测试,仅按示例提供。它不适用于复制/粘贴!)
Dim fso as Object
Set fso = CreateObject("Scripting.FileSystemObject")
Dim ts as TextStream
if (fso.FileExists("Path\to\file.txt") then 'Also could be a range variable's value
'Get file contents
set ts = fso.OpenTextFile("Path\to\file.txt")
'Loop while not end of file
Do While Not ts.AtEndOfStream
'Set a cell's value to the read line
Range(something).value = ts.ReadLine
Loop
End If
答案 1 :(得分:0)
我最终这样做了,效果很好:
Sub t()
Dim fso As Scripting.FileSystemObject
Dim ts As Scripting.TextStream
Dim strPath As String
strPath = "\\corp.com\rootDisc Usage\"
Set fso = New Scripting.FileSystemObject
For Z = 0 To 12 'variable for next month column range after each prior column range completes.
For s = 0 To 12 'Counter for limiting looping and start the next server to process.
y = (s * 13) 'Increments after initial loop to the next server file name for processing.
If fso.FileExists(strPath & Range("MMYY").Offset(y, Z).Value) = True Then
If Range("MMYY").Offset(y + 1, Z) = "" Then
'Locates next server file to process by referencing the file name in the correct range and prevents
'processing and overwriting data in the spreadsheet if the data is already populated.
Set ts = fso.OpenTextFile(strPath & Range("MMYY").Offset(y, Z).Value, ForReading)
'opens the correct file matching the file name in the offset specified range cell, in read only mode
i = (1)
Do
Range("MMYY").Offset(y + i, Z) = ts.ReadLine
i = i + 1
Loop Until ts.AtEndOfStream
ts.Close
End If
Else
'file doesn't exist
End If
Next
'exits data write loop
Next
'exits column processing loop
Z = (Z + 1)
'increments active column offset to the next month column.
Set ts = Nothing
Set fso = Nothing
End Sub