簡體   English   中英

VBA For Next 循環遍歷一個范圍

[英]VBA For Next Loop through a range

對於我的范圍數據的第一行,一切正常。 當我執行“下一個單元格”時,它向下移動到第二行數據,但第一個值來自第二列數據。

示例:數據來自 K:N 列。 第一個數據在第 2 行。當它轉到“下一個單元格”時,該行變為三行,但是 cell.value = 來自 L 列第 3 行而不是 K 列第 3 行的值。這正常嗎? 當我移動到下一個 C 並且行更改時,它不應該從最左邊的列開始嗎? 謝謝!

Function Modifer_Analysis()

Dim modRng As Range
Dim cell As Range
Dim i As Integer
Dim col As Integer
Dim rowTrack As Double
Dim modComp As String

Range("K2:N17914").Select
Set modRng = Selection

rowTrack = 2

For Each cell In modRng

    If rowTrack = cell.row Then

        If i = 0 And IsEmpty(cell.Value) = False Then
            modComp = cell.Value
        Else
        End If

        If i = 1 And IsEmpty(cell.Value) = False Then
            modComp = modComp & "," & cell.Value
        Else
        End If

        If i = 2 And IsEmpty(cell.Value) = False Then
            modComp = modComp & "," & cell.Value
        Else
        End If

        If i = 3 And IsEmpty(cell.Value) = False Then
            modComp = modComp & "," & cell.Value
        Else
        End If

        i = i + 1

    Else

        i = 0
        rowTrack = cell.row
        modComp = ""

    End If

Next cell


End Function

目前尚不清楚您想要實現的目標,但也許更像這樣的事情會是一個好的開始:

Function Modifer_Analysis()

    Dim cell As Range, rw As Range
    Dim modComp As String, sep As String

    'loop over rows
    For Each rw In Range("K2:N17914").Rows 'needs a worksheet qualifier here
        modComp = ""
        sep = ""
        For Each cell In rw.Cells
            'loop over cells in row
            If Len(cell.Value) > 0 Then
                modComp = modComp & sep & cell.Value
                sep = ","
            End If
        Next cell
    Next rw

End Function

暫無
暫無

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

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