首页 文章

为什么我的VBA代码总是跳过我的第一个循环?

提问于
浏览
1

我正在尝试让我的VBA代码循环遍历所有单元格,并在每次遇到单元格中的特定文本时将第二张中已存在的数字的数量减1 . 但是,每当我按步骤运行循环时,它似乎跳过下一个j并且每次都直接进入下一行,这是下一行 . 我的代码是否存在某种格式错误?

Sub DeleteSAC()

Dim count As Integer
Dim i As Integer
Dim j 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
i = 2
j = lastColumn

For i = 2 To lastRow
For j = lastColumn To 1
If Sheet1.Cells(i, j) = "SAC" Then
    count = count - 1
    GoTo NextIteration
End If
Next j
NextIteration:
Next i

Sheet2.Cells(1, 7) = count


End Sub

1 回答

  • 0

    试试这个:-

    Option Explicit
    
            Sub DeleteSAC()
    
            Dim count As Integer
            Dim i As Integer
            Dim j As Integer
            Dim ws1 As Worksheet
            Dim ws2 As Worksheet
            Dim lastRow As Long
            Dim lastcolumn As Long
    
            Set ws1 = Worksheets("Sheet1")
            Set ws2 = Worksheets("Sheet2")
    
    
            lastRow = ws1.Cells(Rows.count, "B").End(xlUp).Row
    
            lastcolumn = ws1.Cells(1, Columns.count).End(xlToLeft).Column
    
            count = ws2.Cells(1, 7).Value
            i = 2
            j = lastcolumn
    
    
            For i = 2 To lastRow
            For j = lastcolumn To 1 Step -1
    
    
            If ws1.Cells(i, j) = "SAC" Then
                count = count - 1
    Exit for
                End If
    
    
            Next j
            Next i
    
            ws2.Cells(1, 7) = count
    
    
            End Sub
    

相关问题