VBA - 解析CSV函数,获取函数输出

时间:2014-04-10 14:28:44

标签: function vba parsing csv

我有一个代码(请参见下文)来解析csv文件。在我想要使用该数据的功能之后,但我不确定该功能的输出是什么或我如何使用它?基本上csv有一列数字,我想在我的主页中复制,但在功能之后如何在子环境中复制/粘贴数据?

非常感谢!

Function ParsefileAsTable(ByVal sNomFichier As String) As Variant
Dim Chaine As String
Dim Ar() As String
Dim var As Variant
Dim nblignes As Long
Dim nbcol As Long
Dim i As Long
Dim iRow As Long, iCol As Long
Dim NumFichier As Integer
Dim Separateur As String * 1

    Separateur = ","
    With Application
        .ScreenUpdating = False
        .EnableEvents = False
    End With

    Close
    NumFichier = FreeFile

    iRow = 0
    Open sNomFichier For Input As #NumFichier

    Do While Not EOF(1)
        Line Input #NumFichier, Chaine
        nblignes = nblignes + 1
        Ar = Split(Chaine, Separateur)
        nbcol = UBound(Ar) + 1
    Loop
    Close #NumFichier

ReDim var(1 To nblignes, 1 To nbcol)

iRow = 0
    Open sNomFichier For Input As #NumFichier
        Do While Not EOF(NumFichier)
                iCol = 1: iRow = iRow + 1
                Line Input #NumFichier, Chaine
                Ar = Split(Chaine, Separateur)
                For i = LBound(Ar) To UBound(Ar)
                    If Not iCol > nbcol Then
                        var(iRow, iCol) = Ar(i)
                        iCol = iCol + 1
                    End If
                Next
        Loop
    Close #NumFichier

    With Application
        .ScreenUpdating = True
        .EnableEvents = True
    End With

ParsefileAsTable = var

End Function

1 个答案:

答案 0 :(得分:1)

函数的输出是Variant类型,由函数本身定义。

Function ParsefileAsTable(ByVal sNomFichier As String) As Variant

函数的返回值是变量var,在End Function之前分配:

ParsefileAsTable = var

你可以从调用子程序把它放到这样的工作表中(通常建议只使用函数来返回值,而不是操纵工作表对象):

Dim var as Variant
var = ParseFileAsTable("C:\mon_fichier.txt")

Range("A1").Resize(UBound(var, 1), UBound(var, 2)).Value = _
    var

编辑我对上面一行进行了修改,以处理基于1的数组(通常它们是0)......

您收到的错误是因为var不是调用过程中定义的变量,因此上面的修订版实例化该变量,然后分配函数的返回值。然后,我们使用var来确定范围的大小(使用Resize)方法,并将数组打印到该范围。