【问题标题】:First the next and previous cells with data in a row Excel VBA首先是下一个和上一个单元格,其中包含一行 Excel VBA 中的数据
【发布时间】:2015-05-07 15:16:55
【问题描述】:

我目前正在尝试编写代码来查看左侧第一个单元格和相关单元格右侧的第一个单元格,并返回这些单元格的列号值。我目前使用的代码使用.Find 方法,它只是将单元格立即返回到相关单元格的右侧/左侧。从屏幕截图中,如果我在循环中的单元格 G2 中,我想分别为 iFirstiLast 返回第 4 列和第 9 列。我实际上是返回 6 和 8。有什么问题?这是我的代码:

Public iLastRow As Long
Public iLastColumn As Long

Sub Interpolate()

    Dim iFirst As Long
    Dim iLast As Long

    'Find Last Row/Column of Data
    iLastRow = Cells.Find("*", searchorder:=xlByRows, searchdirection:=xlPrevious).Row
    iLastColumn = Cells.Find("*", searchorder:=xlByColumns, searchdirection:=xlPrevious).Column

    'Interpolate across each row
    For iRowCounter = 2 To iLastRow
        If Cells(iRowCounter, 2) = "" Then
            'Do nothing if row is empty
        Else
            'Set up interpolation loop
            For iColumnCounter = 2 To iLastColumn - 1
                If Cells(iRowCounter, iColumnCounter) <> "" Then
                    'Do Nothing if Column is populated
                Else
                    iFirst = Cells.Find("*", Cells(iRowCounter, iColumnCounter), searchorder:=xlByColumns, searchdirection:=xlPrevious).Column - 1
                    iLast = Cells.Find("*", Cells(iRowCounter, iColumnCounter), searchorder:=xlByColumns, searchdirection:=xlNext).Column

                End If
            Next iColumnCounter
        End If
    Next iRowCounter

End Sub

电子表格的屏幕截图:

【问题讨论】:

    标签: vba excel


    【解决方案1】:

    我认为问题出在这里:

    Else
        iFirst = Cells.Find("*", Cells(iRowCounter, iColumnCounter), searchorder:=xlByColumns, searchdirection:=xlPrevious).Column - 1
        iLast = Cells.Find("*", Cells(iRowCounter, iColumnCounter), searchorder:=xlByColumns, searchdirection:=xlNext).Column
    End If
    

    改成:

    Else
        iFirst = Cells.Find("*", Cells(iRowCounter, iColumnCounter), searchorder:=xlByRowss, searchdirection:=xlPrevious).Column - 1
        iLast = Cells.Find("*", Cells(iRowCounter, iColumnCounter), searchorder:=xlByRows, searchdirection:=xlNext).Column
    End If
    

    通过xlByRows 进行搜索,而不是通过xlByColumns 在行中水平搜索。

    【讨论】:

    • 这成功了!显然,我不明白搜索顺序。
    • 没关系,发生了。我最初有一个完全不同的答案,然后阅读更多你的代码以意识到你正在做我最初说要做的事情。 :/ 很高兴,点击复选标记接受它作为答案,这样其他人在搜索时就会知道有一个有效的解决方案。
    • 这让我等了 x 分钟才接受答案。别担心,我点击了它。
    • 啊,。忘记了... :)
    猜你喜欢
    • 1970-01-01
    • 2020-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多