首页 > 解决方案 > 如何在 vba 中的循环结束时实现公式?

问题描述

我试图基本上有一个循环来计算我的某些标准。在我的代码结束时,我想使不计算的内容本质上称为“DRSNR”。我知道我可以在我的文件中使用一个简单的公式来使其工作,但我宁愿在我的 VBA 代码中使用这个公式,这样它就可以成为虚拟证明,并且没有人会错误地删除它,因为我不会是唯一的用户。

现在由于某种原因,我的代码在这个地方不起作用:

drsnr = lastrow - sac - count

0出于某种原因,无论如何我总是得到计数。有任何想法吗?我首先认为 mylastrow没有被归为整数,所以我添加了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

标签: excelvbaloopsformula

解决方案


您可能需要移动此行:

drsnr = lastrow - sac - count

前:

Sheet2.Cells(1, 13) = drsnr

drsnrInteger使用 value进行初始化0,直到您为其分配其他值。


推荐阅读