选择行并显示在上方

时间:2018-08-02 08:42:46

标签: excel vba

当用户单击任何行单元格时,我想在工作表顶部的表中显示所选行。

我正在尝试使用此方法:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

    Dim myRowPos As Long
    Dim myRow As Range
    myRowPos = Selection.ListObject.Range.row
    Set myRow = ActiveCell.EntireRow 'I want to select the row in the table ONLY

    'Highlight the entire row here


Cells.Interior.ColorIndex = 0
If IsEmpty(Target) Or Target.Cells.Count > 1 Then Exit Sub
Application.ScreenUpdating = False
With ActiveCell
    Range(Cells(.CurrentRegion.row, .Column), Cells(.CurrentRegion.Rows.Count + .CurrentRegion.row - 1, .Column)).Interior.ColorIndex = 8
End With
Application.ScreenUpdating = True

    'Show above
    If Not myRow Is Nothing And myRowPos >= 9 Then
        Range("EditCountry").Value = myRow.Cells(1, 1)
        Range("EditNodeName").Value = myRow.Cells(1, 2)
        Range("EditNodeId").Value = myRow.Cells(1, 3)
        Range("EditParentNode").Value = myRow.Cells(1, 4)
        Range("EditParentNodeId").Value = myRow.Cells(1, 5)
        Range("EditActive").Value = myRow.Cells(1, 6)
        Range("EditFrom").Value = myRow.Cells(1, 7)
        Range("EditTo").Value = myRow.Cells(1, 8)
    End If

    'Save row in the table with the modified data when clicking a button

End Sub

我的主要问题是: -我只想选择表中的行(不是整个活动行,除了表,该行包含其他数据...) -显示上方的行,如果在该行中进行了编辑,则该信息然后在之前的行中进行编辑(通过单击“更新”按钮)

1 个答案:

答案 0 :(得分:0)

Worksheet_SelectionChange在每次移动光标或单击鼠标时触发。您可以使用Intersect检查表中的单元格是否被单击。将此放在子标题的顶部:

Dim rngTable as Range
Set rngTable = "B9:I349"    ' set a range var to the valid area of the table

If Intersect(rngTable, Target) Is Nothing Then Exit Sub

这不会阻止子程序运行,但是万一它会迅速退出。 您可以随着表的发展以编程方式更新rngTable。