简体   繁体   中英

How to implement a formula at the end of your loop in vba?

I'm trying to essentially have a loop that counts certain criteria for me. At the end of my code I want to make it so that whatever is not counted is essentially called "DRSNR". I know I could use a simple formula in my file to make it work, but I'd rather have the formula in my VBA code so that it becomes dummy proof and no one erases it by mistake as I wont be the only user.

Now for some reason in my code doesn't work at this place:

drsnr = lastrow - sac - count

For some reason I always get the count of 0 no matter what. Any ideas? I first thought that my lastrow wasn't attributed as an integer, so I added Dim lastrow as integer , however that didn't seem to work either.

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

You might need to move this line:

drsnr = lastrow - sac - count

before:

Sheet2.Cells(1, 13) = drsnr

drsnr will be an initialised Integer with value 0 , until you assign it some other value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM