在所选单元格上方找到第一行非空白行

时间:2018-09-05 16:16:52

标签: vba

我想选择所选单元格上方的第一行非空白(减去偏移量)。例如,如果在工作表Machine 1中找到了Grupos Produção,我想返回******* Grupo 1 *******字符串。

********** Grupo  1  ********** 
    Machine 1
    Machine 2

到目前为止,我有以下内容,但没有返回我需要的内容。

    Dim FindString As String
    Dim Rng As Range
    FindString = Lcell.Value
    If Trim(FindString) <> "" Then
        With Sheets("Grupos Produção").Range("A:Z")
            Set Rng = .Find(What:=FindString, _
                            After:=.Cells(.Cells.Count), _
                            LookIn:=xlValues, _
                            LookAt:=xlWhole, _
                            SearchOrder:=xlByRows, _
                            SearchDirection:=xlNext, _
                            MatchCase:=False)
            If Not Rng Is Nothing Then
                Application.Goto Rng, True
                upperRow = .Cells(Rng.Row, Rng.Column - 1).End(xlDown).Row
            Else
                MsgBox "Nothing found"
            End If
        End With
    End If

3 个答案:

答案 0 :(得分:1)

我不确定我是否理解您的代码,但是我认为您正在寻找类似的内容:

...
...
If Not Rng Is Nothing Then
    Do While Rng.Row > 1 And Rng.Offset(-1, 0).Value <> ""
        Set Rng = Rng.Offset(-1, 0)
    Loop
...

一旦找到该单元格,它将一直向上进行,直到找到一个空单元格并在此之前停止。

答案 1 :(得分:0)

这将找到所选单元格上方的第一个非空白单元格(表示行不为空白)。

您需要检查:

  • 如果工作表的其余部分为空,它将返回与您选择的地址相同的地址。
  • 如果所选内容上方的所有单元格都为空,则将从表格底部开始,直到再次到达您的所选内容为止。

正如您所说的第一个非空白单元格,它使用*通配符进行搜索,并使其从使用xlPrevious的选择中查找。

在整个工作表为空的情况下,仍然需要检查rng是否为空。

Sub Test()

    Dim Rng As Range

    With ThisWorkbook.Worksheets("Sheet1").Range("A:Z")
        Set Rng = .Cells.Find(What:="*", _
                              After:=Selection, _
                              LookIn:=xlValues, _
                              LookAt:=xlWhole, _
                              SearchOrder:=xlByRows, _
                              SearchDirection:=xlPrevious)

        If Not Rng Is Nothing Then
            If Rng.Address = Selection.Address Or Rng.Row > Selection.Row Then
                MsgBox "Nothing found"
            Else
                Rng.Select
            End If
        End If

    End With

End Sub

答案 2 :(得分:0)

我根据@Sam的答案设法得到了所需的东西

    If Not Rng Is Nothing Then
                    Do While Rng.Row > 1 And Rng.Offset(-1, 0).Value <> ""
                        Set Rng = Rng.Offset(-1, 0)
                    Loop
                    grupo = Rng.Offset(-1, -1).Value
                    Lcell.Value = grupo
                End If
相关问题