0

我有一个电子表格,我希望自动格式化 A:A 范围,以便字符显示为红色,数字保持相同的颜色。以下宏似乎可以正常工作,但是每次更改单元格中的值时都需要手动运行它:

Sub Red_text()

Dim i As Integer
Dim MyString As String

MyString = ActiveCell.Value

For i = 1 To Len(MyString)
    If IsNumeric(Mid(MyString, i, 1)) = False Then
        ActiveCell.Characters(i, 1).Font.Color = RGB(247, 66, 66)
    End If
Next i

End Sub

所以基本上我需要把它改成一个事件宏,每次编辑时都会重新格式化当前单元格。并将此行为限制在 A:A 范围内。

任何帮助将不胜感激!!

4

1 回答 1

1

首先对您的宏稍作改动:

Sub Red_text(r As Range)

Dim i As Integer
Dim MyString As String

MyString = r.Value

For i = 1 To Len(MyString)
    If IsNumeric(Mid(MyString, i, 1)) = False Then
        r.Characters(i, 1).Font.Color = RGB(247, 66, 66)
    End If
Next i
End Sub

并且还在工作表代码区域中包含以下事件宏:

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim A As Range
    Set A = Range("A:A")
    If Intersect(A, Target) Is Nothing Then Exit Sub
    Application.EnableEvents = False
        Call Red_text(Target)
    Application.EnableEvents = True
End Sub

事件宏检测到 A 列的条目,然后应用格式。

编辑#1

事件宏必须更改为一次处理多个单元格。删除原始事件宏并使用:

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim A As Range, rBIG As Range, r As Range
    Set A = Range("A:A")
    Set rBIG = Intersect(A, Target)
    If rBIG Is Nothing Then Exit Sub
    Application.EnableEvents = False
        For Each r In rBIG
            Call Red_text(r)
        Next r
    Application.EnableEvents = True
End Sub
于 2013-10-01T16:39:53.500 回答