如图,我要在N8-Y8中的第5位数字和第4位数字之间插入“万”字,并且设置字体为6号字体:
用以下代码:
Sub InsertWanForDecimalNumbers()
Dim cell As Range
Dim cellValue As String
Dim decimalPosition As Integer
Dim sBeforeDecimal As String
Dim sAfterDecimal As String
Dim sBeforeWan As String
Dim sAfterWan As String
' 遍历N8到Y8的单元格
For Each cell In Range("N8:Y8")
If IsNumeric(cell.Value) And Not InStr(cell.Value, "%") > 0 Then
cellValue = CStr(cell.Value)
decimalPosition = InStr(cellValue, ".")
' 判断是否有小数点
If decimalPosition > 0 Then
sBeforeDecimal = Left(cellValue, decimalPosition - 1)
sAfterDecimal = Mid(cellValue, decimalPosition + 1)
Else
sBeforeDecimal = cellValue
sAfterDecimal = ""
End If
' 只对小数点前位数大于等于5的数字进行处理
If Len(sBeforeDecimal) >= 5 Then
sBeforeWan = Left(sBeforeDecimal, Len(sBeforeDecimal) - 4)
sAfterWan = Right(sBeforeDecimal, 4)
' 更新单元格值,插入“万”
If Len(sAfterDecimal) > 0 Then
cell.Value = sBeforeWan & "万" & sAfterWan & "." & sAfterDecimal
Else
cell.Value = sBeforeWan & "万" & sAfterWan
End If
' 设置“万”字的字体大小为6
cell.Characters(Start:=Len(sBeforeWan) + 1, Length:=1).Font.Size = 6
End If
End If
Next cell
End Sub
运行代码后的结果如图所示: