在VBA中返回格式化数组的函数

时间:2013-08-09 18:30:47

标签: arrays function excel-vba vba excel

我有一个函数可以将所有Excel数据打印成一个文本文件,格式如下:

[
['ID', 'Label', 'Longitude', 'Latitude', 'Country', 'Region', 'Ttl_wt_Flw_thru', 'Sum-of-BOL-Wt', 'Count of WDR_Ref', 'Ratio'],
['AEAUH', 'Abu Dhabi, United Arab Emirates', 54.3666667, 24.4666667, 'AE', 'EAME', 66, 30, 8432, 281.066666666667],
['AEDXB', 'Dubai, United Arab Emirates', 55.307485, 25.271139, 'AE', 'EAME', 682, 3, 8369, 2789.66666666667] ]

我编写这样一个数组的代码是:

Function FillSourceArray()
    Dim i As Long, j As Long, s As String
    Dim Lastrow As Double
    Dim S1 As String

    'Opens file
    FilePath = FilePath & "DataArray" & ".txt"
    Open FilePath For Output As #1
    'Read the Source Data
    DataArray = Sheets("Nodes").Cells(1).CurrentRegion.Value
    'Determine the Lastrow
    Lastrow = Sheets("Nodes").Range("A999999").End(xlUp).Row
    Print #1, "["
    'This "for" loop reads all the data in excel sheet into a string
    For i = 2 To UBound(DataArray)
        s = "["
        For j = 1 To UBound(DataArray, 2)
            If IsNumeric(DataArray(i, j)) Then
                s = s & DataArray(i, j) & ", "
            Else
                s = s & "'" & DataArray(i, j) & "', "
            End If
        Next
        If i = Lastrow Then
            Print #1, Replace(s & "]", ", ]", "]")
        Else
            Print #1, Replace(s & "]", ", ]", "],")
        End If
    Next

    Print #1, "]"
    Close #1

我的任务:我想在Excel工作表中读取数据并将其形成一个数组(以上面显示的格式),并将数组返回到函数FillSourceArray()。

我需要从另一个模块调用此函数,我想以这种格式打印数组。

0 个答案:

没有答案