【发布时间】:2020-03-13 03:53:36
【问题描述】:
当前,代码在选择排除行1的任何活动单元格时始终选择活动行的列“ A”,并将该列命名为单元格“我的范围”。这就是前几行所实现的,之后我试图突出显示第 2 行之后的任何活动行,并在选择另一个活动行时清除突出显示。
选择另一个活动行时似乎有问题,因为前一行没有清除颜色。
所以在示例中,我选择了测试 1(第 3 行是活动行):
选择另一个活动行时,例如测试2(第4行现在为活动行),活动行是颜色的,但先前彩色的行3仍在
中彩色每当我选择另一个活动行时,前一行都不会清除它的颜色,我想在第 1 行保持任何颜色(I1 列中的黑色填充),这就是我希望输出在我选择时的样子另一个活动行,所以在这种情况下,我测试 1 是活动行(第 3 行),但是当我选择测试 2(第 4 行)作为活动行时,第 3 行清除它的颜色,如下所示:
这是我正在运行的整个代码:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Application.ScreenUpdating = False 'This speeds up the macro by hiding what the macro is doing
If Target.Row > 1 Then
ActiveWorkbook.Names.Add Name:="MyRange", RefersToR1C1:=Range("A" & (ActiveCell.Row)) 'Defines the name of the ActiveCell as "MyRange" to Autofill VLookup Formula on sheet
Range("A" & (ActiveCell.Row)).Select 'Always Selects Column A depending on the Active Row selecte
Dim TR As Variant
TR = Target.Row > 2
With TR 'With Target refers to the Active Row being selected greater than Row 2
Target.EntireRow.Interior.ColorIndex = 0 'Clears Previous Cells Interior Color
Target.EntireRow.Interior.Color = RGB(243, 243, 123) 'Highlights the entire row that contain the active cell
End With
If Target.Address = "$A$2" Then 'Checks if you have selected Row 2 (The comparison row)
Target.Value = "" 'If Cell A2 is selected (the "Key" comparison cell from the comparison row) then a blank value is inputted
Else
[a2] = ActiveCell 'Makes cell "A2" equal to the Active Cell value (The "Key" in this case)
End If
End If
Application.ScreenUpdating = True 'Must be "True" after running the code to be able to Read/Write the Workbook
End Sub
【问题讨论】:
-
Cells.Interior.ColorIndex = 0是工作表上的每个单元格。上一行似乎会触发您的代码进入循环。 -
是的,我同意这一点,但我怎样才能让它避开第一行。我想也许放一个
If Not语句可以让我保持第一行的格式 -
可能是
if not(target.row=1) then ... -
@TheGridLock 我试过这种方法,它似乎仍在清除第 1 行的内部颜色
-
在代码的开头和结尾添加
application.enableevent = false和true,比如screenupdateing,否则你不应该在代码正文中使用range.select