如何在vba循环结束时实现公式?

时间:2018-12-29 20:26:45

标签: excel vba excel-vba loops formula

我正在尝试建立一个循环,为我计算某些条件。在我的代码结尾,我想制作一个代码,以便将任何未被计数的内容称为“ DRSNR”。我知道我可以在文件中使用一个简单的公式来使其起作用,但我宁愿在VBA代码中包含该公式,以使其成为虚拟证据,并且没有人会误删它,因为我将不是唯一的用户。

现在由于某种原因,我的代码在此位置不起作用:

drsnr = lastrow - sac - count

由于某种原因,无论如何我总是得到0的计数。有任何想法吗?我首先以为我的lastrow并不是整数,所以我加了Dim lastrow as integer,但这似乎也不起作用。

Sub DeleteSAC()
    Dim count As Integer
    Dim sac As Integer
    Dim drsnr As Integer
    Dim i As Integer
    Dim j As Integer
    Dim lastrow As Integer

    Sheets(1).Select

    lastrow = ActiveSheet.Cells(Rows.count, "B").End(xlUp).Row

    'have to keep data in a table for this to actually work as it ctrls+left to the table, which will end where the very last text of any row is
    lastColumn = ActiveSheet.Cells(1, Columns.count).End(xlToLeft).Column

    count = Sheet2.Cells(1, 7).Value
    sac = 0
    i = 2
    j = lastColumn

    For i = 2 To lastrow
    For j = lastColumn To 1 Step -1
    If Sheet1.Cells(i, j) = "SAC" Or Sheet1.Cells(i, j) = "Incorrect address" Then
        count = count - 1
        sac = sac + 1
        GoTo NextIteration
    End If
    Next j
    NextIteration:
    Next i

    Sheet2.Cells(1, 7) = count
    Sheet2.Cells(1, 10) = sac
    Sheet2.Cells(1, 13) = drsnr
    drsnr = lastrow - sac - count

    Sheets(2).Select
End Sub

1 个答案:

答案 0 :(得分:1)

您可能需要移动此行:

drsnr = lastrow - sac - count

之前:

Sheet2.Cells(1, 13) = drsnr

drsnr将被初始化为Integer,其值为0,直到您为其分配其他值为止。