在vba中多次初始化一个数组

时间:2014-04-28 07:45:05

标签: arrays excel vba excel-vba

我正在使用VBA代码插入整数值:

    Dim IgnoreCol() As Integer

    For j = 1 To LastCol
        If Cells(1, j).Value = "IGNORE" Then
            ReDim Preserve IgnoreCol(Temp)
            IgnoreCol(Temp) = j
            Temp = Temp + 1
        End If
    Next

在这部分代码之后,我在我的程序中有一个列数的Int数组 - 现在,在下一个循环中我想接近数组:

For j = 1 To LastCol
    If Not IsInArray(j, IgnoreCol) Then
        DataLine = DataLine + Trim(Cells(Row, j).Value)
    End If
Next j

所以现在我有两个问题:

  1. 假设表格中的两列都没有" IGNORE"在他们的第一个单元格和我的阵列" IgnoreCol"是空的,没有任何细胞被初始化 - 什么条件返回"真"如果数组真的是空的?
  2. 我在另一个循环中使用此代码 - 这意味着,我想初始化我的" IgnoreCol"再次输入之前在此代码末尾的数组(通过初始化我的意思是全部删除,而不是仅在所有单元格中放置0)
  3. 非常感谢!

1 个答案:

答案 0 :(得分:1)

这会测试一个空数组:

Function ArrayIsEmpty(a) As Boolean
Dim temp
  On Error Resume Next
  temp = LBound(a)
  If Err.Number <> 0 Then ArrayIsEmpty = True
End Function

使用Erase功能清除阵列:

Dim a() As Integer
If ArrayIsEmpty(a) Then Debug.Print "Array starts empty" Else Debug.Print "Array NOT empty???"
Redim a(1 To 100)
If ArrayIsEmpty(a) Then Debug.Print "Array empty" Else Debug.Print "Array NOT empty"
Erase a
If ArrayIsEmpty(a) Then Debug.Print "Array NOW empty" Else Debug.Print "Array still not empty"

但我更喜欢使用Dictionary对象(来自“Microsoft Scripting Runtime”,您可以使用VBA编辑器中的“Tools ... References”添加它。)

Dim IgnoreCols As New Dictionary

For j = 1 To LastCol
    If Cells(1, j).Value = "IGNORE" Then
        IgnoreCols.Add j, 1
    End If
Next

For j = 1 To LastCol
    If Not IgnoreCols.Exists(j) Then
        DataLine = DataLine + Trim(Cells(Row, j).Value)
    End If
Next j

......甚至更好,像这样:

Dim IncludeCols As New Dictionary

For j = 1 To LastCol
    If Cells(1, j).Value <> "IGNORE" Then
        IncludeCols.Add j, 1 ' store the cols we *want*
    End If
Next

' now just loop through the list of wanted cols
For j = 0 To IncludeCols.Count
    DataLine = DataLine + Trim(Cells(Row, IncludeCols.Keys(j)).Value)
Next j