首先是连续数据的下一个和上一个单元格Excel VBA

时间:2015-05-07 15:16:56

标签: excel vba excel-vba

我目前正在尝试编写代码,该代码将查看左侧的第一个单元格以及相关单元格右侧的第一个单元格,并返回这些单元格'列号值。我目前使用.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

电子表格截图:
screenshot

1 个答案:

答案 0 :(得分:0)

我认为问题在于:

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进行搜索,以横向搜索整行。