我正在使用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
所以现在我有两个问题:
非常感谢!
答案 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