【发布时间】:2015-11-24 13:07:02
【问题描述】:
我想将来自多个 .txt 文件的数据存储在 1 个工作表中。另外,我希望第一个单元格包含文件名而不是文件路径(如果可能),以便稍后将其链接到图表。数据中还有最多 7 列,而行数是可变的,每个额外的数组由一个空列分隔。
Dim myFile As String
Dim myValue As Integer
Dim rData As Integer
Dim Data As String
Dim LineArray() As String
Dim DataArray() As String
Dim TempArray() As String
Dim Delimiter As String
Dim row As Integer
Dim counter As Integer
Dim counterArrSep As Integer
Dim FileName As String
Sub Button1_Click()
'Input number of blades
myValue = InputBox("Please enter the number of employees below", "number of employees", vbOKCancel)
'Cancel (doesn't work properly)
If myValue = 0 Then
Exit Sub
End If
'Inputs
Delimiter = " "
row = 1
'Populate the table
Do While counter < myValue
'.txt file processing
'Show open file dialog box
myFile = Application.GetOpenFilename()
'Cancel
If myFile = "False" Then
Exit Sub
End If
'Get file name (doesn't work)
FileName = Dir(myFile, vbDirectory)
Dim DataArray()
DataArray(counterArrSep, 0) = FileName
'Open file
rData = FreeFile
Open myFile For Input As rData
'Store file content inside a variable
Data = Input(LOF(rData), rData)
'Close file
Close rData
'Separate Out lines of data
LineArray() = Split(Data, vbCrLf)
'Read Data into an Array Variable
For x = LBound(LineArray) To UBound(LineArray)
If Len(Trim(LineArray(x))) <> 0 Then
'Split up line of text by delimiter
TempArray = Split(LineArray(x), Delimiter)
'Determine how many columns are needed
col = UBound(TempArray)
'Re-Adjust Array boundaries
ReDim Preserve DataArray(col, row)
'Load line of data into Array variable
For y = LBound(TempArray) To UBound(TempArray)
DataArray(y + counterArrSep, row) = TempArray(y)
Next y
End If
'Next line
row = row + 1
Next x
'Clear array
Erase TempArray
'Increments the count to get another file
counter = counter + 1
'Adds space between each arrays in the Worksheet
counterArrSep = counterArrSep + 8
Loop
End Sub
.txt 文件如下所示: ...\employees\John.txt
apples pears oranges carrots
4 5 34 2
43 5,5 4 43
6 54 9 7,5
41,5 55 0 2
...\employees\Steve.txt
apples pears oranges carrots cabbages
6 56 6 2 0
4 1 4 12 5
0 7 9 7 6
0 12 1 5 3
1 44 3 6 0
4 4 4,5 6 23
【问题讨论】:
-
那么到底是什么问题?您应该将代码拆分为几个过程。制作一个获取所选文件夹中所有文件的文件。然后让另一个文件同时导入一个文件,并通过将文件名作为参数传递来从第一个文件调用第二个过程。现在我猜你在浏览文件时遇到了问题,对吧?
-
顺便说一句:你真的应该更好地构建你的代码。例如,在过程之外声明整个模块的所有变量是没有意义的。将您的问题分解为更多更小的问题并一一解决。目前你离解决方案真的很远,你有很多问题。确定您的项目结构并在确定一个问题后返回。
-
对不起 VBA 几年前。我试着把我记得的东西放在一起。
标签: excel vba multidimensional-array