ExcelVBA運用Excel的【條件格式】(二) |
前面知識點回顧 1. 訪問 FormatConditions 集合 ? ? ?Range.FormatConditions 2. 添加條件格式 ? ? ?FormatConditions.Add 方法 語法 表達式。添加 (類型、 運算符、 Expression1、 Expression2) 3. 修改或刪除條件格式 4. 清除所有條件格式 |
一、下面我們可以應用宏錄制功能
【問題】查找包含“飛狐外傳”的單元格顯示的自定義格式
操作試一下
得到代碼如下
Sub 宏4()
'
' 宏4 宏
'Range("A1:F36").SelectSelection.FormatConditions.Add Type:=xlTextString, String:="飛狐外傳", _TextOperator:=xlContainsSelection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
With Selection.FormatConditions(1).Font.Color = -16383844.TintAndShade = 0
End With
With Selection.FormatConditions(1).Interior.PatternColorIndex = xlAutomatic.Color = 13551615.TintAndShade = 0
End WithSelection.FormatConditions(1).StopIfTrue = False
End Sub
二、學習相關知識
可以看到是幾個參數:
Type:=***,String:=***,TextOperator:=***
網站查詢一下
三、下面我們自己進行相關的修改及優化
(1)【問題】查找包含“飛狐外傳”的單元格顯示的自定義格式
效果先看圖
修改完成代碼如下
Sub HighlightCellsContainingText飛狐外傳()Dim ws As WorksheetDim searchText As StringDim lastRow As Long, lastCol As LongDim cell As Range' 設置工作表Set?ws?=?ActiveSheet' 設置要搜索的文本searchText?=?"飛狐外傳"???'?修改為你需要搜索的字符' 清除之前的條件格式ws.Cells.FormatConditions.Delete' 添加新的條件格式With?ws.UsedRange.Cells.FormatConditions.Add(Type:=xlTextString,?String:=searchText,?TextOperator:=xlContains).Interior.Color = RGB(255, 0, 0) ' 設置為紅色背景.StopIfTrue = FalseEnd WithMsgBox "所有包含 '" & searchText & "' 的單元格已被高亮顯示。", vbInformation
End Sub
繼續拓展一下功能
(2)【問題】查找開頭為文字‘開頭’兩個字的單元格顯示自定義格式
看效果圖
代碼如下
Sub HighlightCellsContainingText開頭文字()Dim ws As WorksheetDim searchText As StringDim cell As Range' 設置工作表Set ws = ActiveSheet' 設置要搜索的文本searchText = "開頭"' 清除之前的條件格式ws.Cells.FormatConditions.Delete' 添加新的條件格式With ws.UsedRange.Cells.FormatConditions.Add(Type:=xlTextString, String:=searchText, TextOperator:=xlBeginsWith).Interior.Color = RGB(10, 255, 0) '設置為xx背景.StopIfTrue = FalseEnd WithMsgBox "‘開頭’為" & searchText & "' 的單元格已被高亮顯示。", vbInformation
End Sub
如果你想要其他功能就自己可以拓展
如:
(3)結尾是“***”文字的情況
(4)不包含‘***’文字的情況
---------------
如果你在此學習到東西,請轉發給大家免費學習