首页 > 解决方案 > 如何将 CSV 数据导入多个数组并通过 VBA 中的函数或子返回多个数组?

问题描述

我想创建一个导入 CSV 文件的 VBA 加载项,将数据列拆分为单独的数组并将这些多个数组返回给调用此加载项的子程序。不确定解决此问题的最佳方法是什么。

例如,我的数据文件夹包含许多 CSV 文件,每个文件有 5 列数据(第一列是日期,其余列是数字数据。有一行标题)。

我还有几个不同的工作簿,它们对这些 CSV 文件执行不同类型的分析。因此,我不想在每个工作簿中重复使用相同的导入 csv 数据函数或子函数,而是想创建一个加载项来执行此导入函数。

理想情况下,此加载项将为每个 CSV 文件返回 5 个单独的数组。如果没有,如果它返回一个 5 列数组,我会没问题。

代码将类似于(SomeAnalysis Sub 在其中一个工作簿中,ImportCSV 是加载项函数或 Sub,ncsv 是要评估的 CSV 文件的数量):

Sub SomeAnalysis()

  For n = 1 to ncsv
    [arr1,arr2,arr3,arr4,arr5]=ImportCSV(filename(n))
    'Perform the analysis
  next n

End Sub

标签: arraysexcelvbacsv

解决方案


最后用我在网上找到的一些代码来解决它。希望这对你们中的一些人有用。

Option Explicit
Option Base 1

'Import CSV file function: Returns an array of data or multiple arrays
Public Function ImportCSV(filename As String, Optional splitarray As Boolean = True, Optional incheaders As Boolean = True) As Variant()
Dim fnum As Integer                         'file number
Dim datafile As String                      'raw datafile
Dim lines As Variant                        'breaking the file into lines
Dim one_line As Variant                     'temp data rows to split in loop
Dim nrows As Long, ncols As Integer         '# data rows and columns
Dim arr() As Variant                        'jagged data array (i.e. array of arrays)
Dim colarr() As Variant                     'component arrays in arr()
Dim h As Integer                            'flag for include header option
Dim r As Long, c As Integer                 'counters

'Load file
fnum = FreeFile
Open filename For Input As fnum
datafile = Input$(LOF(fnum), #fnum)
Close fnum

'Break file into lines
lines = Split(datafile, vbCrLf)

'Dimension the array
h = IIf(incheaders, 0, 1)
nrows = UBound(lines) - h
one_line = Split(lines(0), ",")
ncols = UBound(one_line)

'Choice to use jagged arrays to split data columns
If splitarray = True Then
    ReDim arr(1 To ncols + 1)
    For c = 0 To ncols
        ReDim colarr(1 To nrows)
        arr(c + 1) = colarr
    Next c
    'Copy data into array
    For r = 0 To nrows - 1
        If Len(lines(r)) > 0 Then
            one_line = Split(lines(r + h), ",")
            For c = 0 To ncols
                arr(c + 1)(r + 1) = one_line(c)
            Next c
        End If
    Next r
Else
    ReDim arr(nrows, ncols + 1)
    'Copy data into array
    For r = 0 To nrows - 1
        If Len(lines(r)) > 0 Then
            one_line = Split(lines(r + h), ",")
            For c = 0 To ncols
                arr(r + 1, c + 1) = one_line(c)
            Next c
        End If
    Next r
End If
ImportCSV = arr
End Function

推荐阅读