[英]How to Change Multiple Format Parameters of a Cell Based on Its Value?
我想編寫一個基於單元格值更改選定單元格范圍的樣式屬性的代碼。
當我僅更改文本顏色或字體時有效,但由於代碼不執行任何操作,因此我向每個參數添加了多個參數。 我也沒有得到錯誤。
Dim userRange As Range
Set userRange = Application.InputBox("Select a range", Type:=8)
For Each cell In Selection
If cell.Value < 0 Then cell.Font.FontStyle = "Comic Sans MS" & cell.Font.Size = 18 & cell.Font.Color = vbRed
If cell.Value >= 0 And cell.Value <= 500 Then cell.Font.Bold = True & cell.Font.Italic = True & cell.Font.Underline = True
If cell.Value > 500 And cell.Value <= 1000 Then cell.Font.FontStyle = "Monotype Corsiva" & cell.Font.Color = vbBlue & cell.Font.Underline = xlUnderlineStyleDouble
If cell.Value > 1000 Then cell.Font.FontStyle = "Arial" & cell.Font.Bold = True & cell.Font.Italic = True & cell.Interior.Color = vbGreen & cell.Font.Color = vbWhite
Next cell
我想我真的很接近,但我似乎無法弄清楚自己在做什么錯! 我希望我的解釋很清楚,因為我不太習慣編程/腳本編寫。
提前致謝!
我認為這應該解決它。 您的舊代碼並未執行每一行。 您必須插入:
而不是&
的空格。 此外,如果您使用“ With
功能來保存一些鍵入內容,它還會保存一些鍵入內容。 還要注意,您正在使用ActiveCell
,請確保這是故意的。
Dim userRange As Range, d As Double, cell As Range 'added more variables
Set userRange = Application.InputBox("Select a range", Type:=8)
For Each cell In userRange.Cells
d = cell.Value
With cell.Font
If d < 0 Then
.FontStyle = "Comic Sans MS"
.Size = 18
.Color = vbRed
End If
If d >= 0 And d <= 500 Then
.Bold = True
.Italic = True
.Underline = True
End If
If d > 500 And d <= 1000 Then
.FontStyle = "Monotype Corsiva"
.Color = vbBlue
ActiveCell.Underline = xlDouble ' is this right?
End If
If d > 1000 Then
.FontStyle = "Arial"
.Bold = True
.Italic = True
.Color = vbGreen 'this is being undone in the next line of code.
.Color = vbWhite
End If
End With
Next cell
您定義了userRange,但稍后您將遍歷選擇中的單元格。 另外,您使用不正確。 您可以嘗試以下方法:
Dim userRange As Range
Set userRange = Application.InputBox("Select a range", Type:=8)
For Each cell In userRange
If cell.Value < 0 Then
cell.Font.FontStyle = "Comic Sans MS"
cell.Font.Size = 18 & cell.Font.Color = vbRed
End If
If cell.Value >= 0 And cell.Value <= 500 Then
cell.Font.Bold = True & cell.Font.Italic = True
cell.Font.Underline = True
End If
If cell.Value > 500 And cell.Value <= 1000 Then
cell.Font.FontStyle = "Monotype Corsiva"
cell.Font.Color = vbBlue
cell.Font.Underline = xlUnderlineStyleDouble
End If
If cell.Value > 1000 Then
cell.Font.FontStyle = "Arial"
cell.Font.Bold = True
cell.Font.Italic = True
cell.Interior.Color = vbGreen
cell.Font.Color = vbWhite
End If
Next cell
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.