我正在寻找一个VBA用户定义函数,该函数将读取.csv文件的内容并将结果作为数组返回以填充工作表的单元格,如下所示:
=CSV_Read("path/to/file.csv")
我找到this但看起来是专有/共享软件。有谁知道任何替代品?或者在VBA中推广自己的最佳方法是什么?
答案 0 :(得分:4)
在您的VBA代码中,添加对“Microsoft Scripting Runtime”的引用 添加模块,粘贴以下代码。
Option Explicit
Public Function CSV_Read(ByVal path As String) As Variant
Dim fso As Scripting.FileSystemObject
Dim tsm As Scripting.TextStream
Dim data
Dim text As String
Dim allRowsInArray As Variant
Dim currentLineToArray As Variant
Dim columnCount As Integer
Dim columnCounter As Integer
Dim rowCounter As Integer
Dim rowCount As Integer
Set fso = New Scripting.FileSystemObject
Set tsm = fso.OpenTextFile(path, ForReading)
rowCounter = 0
If Not tsm.AtEndOfStream Then
text = tsm.ReadAll
tsm.Close
Set tsm = Nothing
Set fso = Nothing
allRowsInArray = Split(text, vbCrLf)
rowCount = UBound(allRowsInArray)
Do While rowCounter < (rowCount + 1)
currentLineToArray = Split(allRowsInArray(rowCounter), ",")
If Not IsArray(data) Then
columnCount = UBound(currentLineToArray)
ReDim data(rowCount, columnCount)
End If
For columnCounter = 0 To columnCount
data(rowCounter, columnCounter) = currentLineToArray(columnCounter)
Next
rowCounter = rowCounter + 1
Loop
End If
CSV_Read = data
End Function
示例CSV文件数据
a,b,c,d,e,f,g
1,2,3,4,5,6,7
7,6,5,4,3,2,1
q,w,e,r,t,y,u
查看数据,它有7列和4行。
现在,转到单元格A1并选择从单元格A1到G4的范围
在单元格A1中键入公式(=CSV_Read("the full path to your csv file")
(保持选择不变)。
重要:强>
完成输入公式后,按 CTRL + SHIFT + ENTER 。这是数组公式。