如果语句结果相互覆盖VBA

我正在经历我的循环输出的问题。 随着子运行,我可以看到最后的IF语句的结果被第二个结果覆盖。 我的代码结构如下:

for i = 1 to 5 for j = 1 to 50 for each events.value in eventArray if events.value = arrayElem then if cells(i,j).value = "x" then type = "col1" elseif cells(i,j).value = "y" then date = "col2" elseif cells(i,j).value = "z" then num = "col3" end if count = count + 1 activeworkbook.worksheets("output").cells(count + 1, 1) = type activeworkbook.worksheets("output").cells(count + 1, 2) = date activeworkbook.worksheets("output").cells(count + 1, 3) = num end if next arrayElem if cells(i,j).value = "a" then name = "row1" elseif cells(i,j).value = "b" then size = "row2" elseif cells(i,j).value = "c" then height = "row3" end if activeworkbook.worksheets("output").cells(count + 2, 1) = name activeworkbook.worksheets("output").cells(count + 2, 2) = size activeworkbook.worksheets("output").cells(count + 2, 3) = height next j next i 

显然这些是dumbyvariables和结果,但总体结构与真实代码相同。 我可以看到正在打印的“名称”,“大小”和“高度”,但是它们被“types”,“date”和“数字”取代。 我如何防止这种情况发生? 每次发现新事件时,我都需要将其相关特性打印到“输出”表中的新行中。

考虑下面的代码的简化版本:

 For i = 1 To 100 If x = y Then rowNum = rowNum + 1 Cells(rowNum + 1, 1) = "A" End If Cells(rowNum + 2, 1) = "B" Next 

每次循环都写出一两个东西(如果x = y为真,则返回两个,如果不是,则返回一个),但是您只是将行号加1或1(如果x = y则为true如果不是,则为零)。 即使你知道x总是等于y,你仍然试图写出两行信息,但只增加一行计数器。

假设你没有试图用循环中下一个迭代中的“A”来代替我的例子中的“B”,你应该将代码改为:

 For i = 1 To 100 If x = y Then rowNum = rowNum + 1 Cells(rowNum, 1) = "A" End If rowNum = rowNum + 1 Cells(rowNum, 1) = "B" Next