将字符串的变体附加到空的变体数组

时间:2019-06-25 21:06:27

标签: vba

我想将字符串值数组重复添加到主数组,该主数组最初是空的。我无法附加它。

Sub main()

    Dim num As Integer, root As String, pathToFile As String, allOf As Variant, someOf As Variant
    Dim i As Integer, opts() As String, val As Integer
    root = Application.ActiveWorkbook.Path
    pathToFile = root & "\" & "name" & ".txt"

    num = 5  ' the number of files I may have

    For i = 0 To num - 1  ' loop over all the files
        ReDim Preserve opts(i)
        someOf = read_whole_file(pathToFile)  ' read the file into variant
        For val = LBound(someOf) To UBound(someOf)  ' run through the array
            ' -- append someOf to allOf and loop
            Dim Nmbr As Integer
            On Error Resume Next
            Err.Clear
            If allOf.Value = "Empty" Then
                Nmbr = UBound(allOf)
                allOf(0) = someOf(0)
            Else
                ReDim Preserve allOf(UBound(allOf) + 1)
                allOf(UBound(allOf)) = someOf(val)
            End If
        Next val
    Next i
End Sub

Function read_whole_file(filePath As String) As Variant
    Dim sWhole As String
    Open filePath For Input As #1
        sWhole = Input$(LOF(1), 1)
    Close #1
    read_whole_file = Split(sWhole, vbNewLine)
End Function

文本文件的内容:

” 你好

文字

文件 “

2 个答案:

答案 0 :(得分:0)

这是VBA。不要使用数组使用集合。

Sub main()

    Dim num As Integer, root As String, pathToFile As String, allOf As Collection, someOf As Variant
    Set allof = new collection
    Dim i As Integer, opts() As String, val As Variant
    root = Application.ActiveWorkbook.Path
    pathToFile = root & "\" & "name" & ".txt"

    num = 5  ' the number of files I may have

    For i = 0 To num - 1  ' loop over all the files

        someOf = read_whole_file(pathToFile)  ' read the file into variant
        For Each val In someOf ' run through the array
            alloff.Add val
        Next
    Next i
End Sub

答案 1 :(得分:0)

在您的代码中,您说有5个文件:

   num = 5  ' the number of files I may have

,但是您在此之前设置了path_to_file。更重要的是,您不会在循环内更改path_to_file,也不会将任何修饰符传递给read_whole_file。因此,您的代码将从同一文件中读取5次。

在使用allOf之前,也不要为其设置任何值。您甚至都不知道它是什么类型(除Variant之外),因此检查.Value是没有意义的,应该会导致编译错误。由于您的On Error语句,该部分可能会被忽略,因此不会发生预期的操作。

如何修复:

  • 在模块顶部添加Option Explicit始终

  • 删除On Error处理-如果您认为可能存在一些问题,请在程序逻辑中解决。

奖金:您已经知道有多少次迭代了,而不是每次ReDimopts(I),所以在进入循环之前,只需ReDim一次。循环。