'Worksheet_SelectionChange(ByValTarget As Range) '當工作表中 選擇的單元格 改變時觸發(fā)該事件. '參數(shù)Target代表工作表中所選取的單元格或單元格區(qū)域 '例:高亮顯示單元格所在的行列 '下面的代碼高亮顯示工作表單元格所在的行列:(類似于wps 方便查看 不容易看錯行,但是會清掉已有戳色塊) Private Sub Worksheet_SelectionChange5(ByVal Target As Range) Cells.Interior.ColorIndex = xlNone With Target .EntireRow.Interior.Color = vbRed .EntireColumn.Interior.Color = vbRed End With End Sub 對應VBA 高亮顯示單元格所在行列 還可以(最終也會清除掉已有著色單元格) Public LastRange As Range ' 用于存儲上次突出顯示的區(qū)域 Public currCell As Range 'currCell 當前單元格 Sub HighLight2() On Error Resume Next Dim dataRange As Range Dim currRange As Range Dim lastRow As Long Dim lastCol As Long '獲取工作表的數(shù)據(jù)區(qū)域,這里假設數(shù)據(jù)區(qū)域從A1開始,向右和向下延伸 With ActiveSheet lastRow = .UsedRange.Rows.Count lastCol = .UsedRange.Columns.Count Set dataRange = .Range("A1").Resize(lastRow, lastCol) '檢查上次是否有突出顯示的區(qū)域,如果有,還原它們的格式 If Not LastRange Is Nothing Then LastRange.Interior.ColorIndex = xlNone ' 清除上次的突出顯示 Set LastRange = Nothing ' 清除上次突出顯示的區(qū)域 End If '檢查選定的單元格是否在數(shù)據(jù)區(qū)域內 '判斷當前單元格是否在數(shù)據(jù)區(qū)域之內,如果在的話,就把當前區(qū)域設置在數(shù)據(jù)區(qū)域之內,以當前單元格為中心的十字區(qū)域;如果當前單元格不在數(shù)據(jù)區(qū)域之內,則把當前區(qū)域設置為以當前單元格為中心的十字區(qū)域(整行、整列)。 If Not Intersect(currCell, dataRange) Is Nothing Then '當前單元格和工作表區(qū)域的交集 Set currRange = Union(currCell.EntireRow, currCell.EntireColumn) ' Set currRange = Intersect(currRange, dataRange) ' Else Set currRange = Union(currCell.EntireRow, currCell.EntireColumn) End If '對當前區(qū)域標色,可以根據(jù)需要調整設置 currRange.Interior.Color = RGB(245, 245, 220) '把當前區(qū)域賦值給LastRange,以備在選擇單元格變化、工作表切換、文件關閉時,清除其格式。 Set LastRange = currRange End With End Sub Private Sub Worksheet_Deactivate() If Not LastRange Is Nothing Then LastRange.Interior.ColorIndex = xlNone ' 清除上次的突出顯示 Set LastRange = Nothing ' 清除上次突出顯示的區(qū)域 End If End Sub Private Sub Worksheet_SelectionChange(ByVal Target As Range) Set currCell = Target.Cells(1, 1) Call HighLight End Sub Private Sub Workbook_BeforeClose(Cancel As Boolean) If Not LastRange Is Nothing Then LastRange.Interior.ColorIndex = xlNone ' 清除上次的突出顯示 Set LastRange = Nothing ' 清除上次突出顯示的區(qū)域 End If ThisWorkbook.Save End Sub |
|
來自: 十月波波 > 《WorkSheet 工作表事件》