我正在尝试更改一系列单元格中特定单词的字体。因此,在A2的范围:Q1000中,如果单词Risk
或High
在单元格中,则字体应更改为红色并为粗体。下面是我到目前为止汇总的代码。
Sub Font_Change()
Dim dData As Range
Dim Name As String
Set dData = Sheets("Sheet1").Range("A2:Q10000")
For Each Cell In dData
If Cell = "Risk" Then
Cell.Font.Color = 2
Cell.Font.Bold = True
ElseIf Cell = "Medium" Then
Cell.Font.Bold
ElseIf Cell = "Hign" Then
Cell.Font.Color = 2
Cell.Font.Bold = True
End If
Next
End Sub
答案 0 :(得分:0)
您的代码非常接近!
它可以用另一种更容易管理的方式编码,但会获得相同的结果
Sub Font_Change()
Dim dData As Range
Dim Name As String
Dim cell As Variant
Set dData = Sheets("Sheet1").Range("A2:Q10000")
For Each cell In dData
With cell
Select Case cell.Value
Case "Risk", "High"
.Font.Color = 2
.Font.Bold = True
Case "Medium"
.Font.Bold
End Select
End With
Next cell
End Sub
对于与Like语句结合使用的Case语句,它的编码方式略有不同(即Like "*Risk*"
):
我已经在@ dasg7的回答UCase(str1)
中加入了案例覆盖,以及完成相同InStr(str1, str2) > 0
的不同方式:
Option Compare Text
Sub Font_Change()
Dim dData As Range
Dim Name As String
Dim cell As Variant
Set dData = Sheets("Sheet1").Range("A2:Q10000")
For Each cell In dData
With cell
Select Case True
Case UCase(cell.value) like "*RISK*" or UCase(cell.value) like "*HIGH*"
.Font.Color = vbRed
.Font.Bold = True
Case InStr(cell.Value, "medium") > 0
.Font.Color = vbYellow
.Font.Bold = True
Case Else
.Font.Color = vbBlack
.Font.Bold = False
End Select
End With
Next cell
End Sub
答案 1 :(得分:0)
尝试这样的事情:
Sub tests()
For Each cell In Range("A2:Q1000")
If UCase(cell.Value) Like "*RISK*" Or UCase(cell.Value) Like "*HIGH*" Then
cell.Font.Color = vbRed
cell.Font.Bold = True
End If
If UCase(cell.Value) Like "*MEDIUM*" then cell.Font.Color = vbRed
Next cell
End Sub