2014-04-28 81 views
0

我工作的一个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 

所以现在我有2个问题:

  1. 说,无论是的表单中的列在其第一个单元格中具有“IGNORE”,而我的数组“IgnoreCol”为空,并且没有任何单元格被初始化 - 如果数组真的为空,那么返回“True”的条件是什么?
  2. 我在另一个循环内部使用这段代码 - 这意味着,我想在这段代码的末尾初始化我的“IgnoreCol”数组,然后再次输入它(通过初始化我的意思是删除所有,而不是全部放入0例如细胞)

非常感谢!

+0

1'如果UBOUND(IgnoreCell)> 0',2'REDIM保留IgnoreCell(0)'? –

+0

@mehow UBound(IgnoreCell)返回“TypeMismatch”,因为没有任何单元格被初始化 – Bramat

+0

TypeMismatch?如果数组尚未初始化,通常它的下标超出范围 –

回答

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对象(从“微软脚本运行时“,您可以在VBA编辑器中使用”工具...参考“添加脚本)。

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 
+0

非常感谢!有用!!但现在我有一个不同的问题 - 如果行中有“#N/A”,那么“DataLine = DataLine + Trim(Cells(Row,j).Value)”行将返回错误消息...你有任何想法如何克服这??再次感谢!!! – Bramat

+0

尝试在违规部分添加一个'IsError()'测试。也许可以将单元格值转移到自己的行中,然后使用'IsError'来决定是否使用该值或者为#NA做适当的操作,然后执行append。 –