【问题标题】:VBA For Next Loop through a rangeVBA For Next 循环遍历一个范围
【发布时间】:2020-02-13 18:50:49
【问题描述】:

对于我的范围数据的第一行,一切正常。当我执行“下一个单元格”时,它会向下移动到第二行数据,但第一个值来自第二列数据。

示例:数据来自 K:N 列。第一个数据在第 2 行。当它转到“下一个单元格”时,该行变为 3,但 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

【问题讨论】:

  • 对于每个移动然后向下
  • 你想用这段代码完成什么?你将如何使用结果字符串modComp?您是否打算拆分它以获得范围内非空单元格的数组?
  • 我每行有四列 MOD 数据。我想连接有值的单元格。在某些行中,它们都将为空,而在其他行中,所有四个都将被填充。我使用“,”来分隔它们,并希望避免连接空白值并以“,”结尾。

标签: excel vba


【解决方案1】:

目前尚不清楚您要达到的目标,但也许更像这样的事情会是一个好的开始:

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

【讨论】:

  • 感谢您的帮助。我的主要问题是我在处理数据之前循环到下一个单元格。
猜你喜欢
  • 1970-01-01
  • 2016-05-21
  • 2015-01-07
  • 2011-12-11
  • 2019-11-14
  • 1970-01-01
  • 2018-05-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多