簡體   English   中英

VBA對於下一個循環,直到列的最后一行,但不是工作表的最后一行

[英]VBA For next loop until last row of a column though not last row of sheet

我正在嘗試運行For Next循環,直到特定列的最后一行(而不是工作表的最后一行)。 因此,列表的第一部分在F列中有數據,而第二部分則沒有。 我只希望宏應用於該第一部分。 由於某種原因,該循環僅使用某些命令貫穿第一部分,而不適用於我現在嘗試執行的那些部分。 (我知道將兩個部分手動分開然后運行它會很容易,但是它讓我發瘋了,不知道我做錯了什么:))。

這是代碼:

Dim i As Integer
Dim g As Double
g = 0.083333333
Dim lastrow As Long
lastrow = Sheets("zm").Range("f" & Rows.Count).End(xlUp).Row

Sheets("zm").Activate

For i = 2 To lastrow

    If Sheets("zm").Cells(i, 1) = Sheets("zm").Cells(i + 1, 1) And Sheets("zm").Cells(i, 5) = Sheets("zm").Cells(i + 1, 5) And Sheets("zm").Cells(i + 1, 6) - Sheets("zm").Cells(i, 7) < g Then
        Sheets("zm").Cells(i + 1, 7).Copy
        Sheets("zm").Cells(i, 7).Select
        ActiveSheet.Paste
        Application.CutCopyMode = False
        Sheets("zm").Rows(i + 1).Delete
    End If

Next i

謝謝你的幫助!

避免Select / Selection和/或Activate / ActiveXXX

嘗試這個:

Option Explicit

Sub main()
    Dim i As Long, lastrow As Long
    Dim g As Double
    g = 0.083333333

    With Worksheets("zm")
        lastrow = .Cells(.Rows.Count, "F").End(xlUp).Row

        For i = lastrow To 2 Step -1
            If .Cells(i, 1) = .Cells(i + 1, 1) And .Cells(i, 5) = .Cells(i + 1, 5) And .Cells(i + 1, 6) - .Cells(i, 7) < g Then
                .Cells(i + 1, 7).Copy Destination:=.Cells(i, 7)
                .Rows(i + 1).Delete
            End If
        Next i
    End With
End Sub

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM