如果语句结果覆盖了彼此的VBA

时间:2016-09-22 19:44:58

标签: excel vba excel-vba if-statement for-loop

我的循环输出出现问题。当子运行时,我可以看到最终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

显然这些是dumby变量和结果,但整体结构与实际代码相同。我可以看到“name”,“size”和“height”被打印,但随后它们被“type”,“date”和“num”取代。我该如何防止这种情况发生?每次发现新事件时,我都需要它来打印打印到“输出”表中新行的相关特征。

1 个答案:

答案 0 :(得分:1)

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

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件),但只是将行号增加零或一(如果是x = y为真,如果不是则为零。即使你知道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