在VBA中使用数组debugging

当名字在第8列中有“X”时,我需要编写一个将名字(位于第二列)中的名称存储在数组中的程序,但是我无法将名称放入数组中。 当我现在运行它,我得到一个空值的数组中的值。 经过一些debugging之后,我发现i值指示数组中的哪个点被选中,结果是0,这不是我想要的。

代码如下:

Dim rowCount As Integer Dim duplicateNames(100) As String Dim duplicateNameCounter As Integer duplicateNameCounter = 0 'Count the number of rows' rowCount = WorksheetFunction.CountA(Range("B1:B5000")) 'Find the names with an X next to them and put them in the array' For i = 1 To 100 If Cells(i, 8).Value = "X" Then MsgBox ("Found a name to put in the array!") duplicateNames(i) = Cells(i, 2).Value duplicateNameCounter = duplicateNameCounter + 1 End If Next i 'Show the contents of the array' For i = 1 To duplicateNameCounter MsgBox ("Here's the slot in the array: " & i & vbNewLine & "Here's the name: " & duplicateNames(i)) Next i 

这是我第一次在VBA中使用数组,所以我认为这是我的问题所在。 我有一个C ++数组的背景,但是这些似乎没有太大的差别。

任何帮助,将不胜感激。 谢谢!

您不像增加For Each循环一样递增duplicateNameCounter 。 我认为这是问题。

假设你在第1行和第100行有一个“X”,但是第8列中的其余单元格是空白的(或者没有任何“X”)。

在这个块的末尾, i将是100 ,并且只有槽1和槽100中才会有名字。但是, duplicateNameCounter只会是2值。

 For i = 1 To 100 If Cells(i, 8).Value = "X" Then MsgBox ("Found a name to put in the array!") duplicateNames(i) = Cells(i, 2).Value duplicateNameCounter = duplicateNameCounter + 1 End If Next i 

因此,当你这样做的时候,你基本上是在For i = 1 to 2 ,这不会给你你期望的结果 – 因为为了正确显示第二个副本,它将不得不达到第100个插槽arrays,它永远不会做。

 For i = 1 To duplicateNameCounter MsgBox ("Here's the slot in the array: " & i & vbNewLine & "Here's the name: " & duplicateNames(i)) Next i 

我认为上面@chancea的评论应该可以解决这个问题。

有几个项目阻止了在Excel中成功执行代码。 Option Explicitbuild议使用,因为它会强制你声明所有的variables,并被认为是一个很好的编程习惯。

 Option Explicit Public Sub asdfasdfasdf() Dim rowCount As Integer, i As Integer Dim duplicateNames() As String Dim duplicateNameCounter As Integer 

将计数器设置为0可以使商店值数组不含空值

 duplicateNameCounter = 0 

您的范围公式仅查找5000行数据,因此已将其更改为扫描整个列以防止遗漏logging

 'Count the number of rows' rowCount = WorksheetFunction.CountA(Range("B:B")) 

在testing中,您不是在search大写和小写X.

 'Find the names with an X next to them and put them in the array' For i = 1 To rowCount If Cells(i, 8).Value = "X" Or Cells(i, 8).Value = "x" Then duplicateNameCounter = duplicateNameCounter + 1 

添加了调整数组的大小,以便数组的大小显示find的存储数量

  ReDim Preserve duplicateNames(duplicateNameCounter) Debug.Print "Found a name to put in the array! " & Cells(i, 2).Value 

您没有在duplicateNames数组上使用duplicateNameCounter值。

  duplicateNames(duplicateNameCounter) = Cells(i, 2).Value End If Next i 'Show the contents of the array' For i = 1 To duplicateNameCounter MsgBox "Here's the slot in the array: " & i & vbNewLine & "Here's the name: " & duplicateNames(i) Next i End Sub 

我把debugging信息写到了即时窗口,加快了代码的运行速度,使得故障排除更加高效。