用vba的宏制作出将所选单元格(包括和此单元格内容重复的其它单元格部分)的字体格式变为红色、加粗。

要求:设计一个命令按钮,作为该功能的启动与关闭开关。要包含SelectionChange事件编程、循环语句、单元格相关属性的使用。各位大哥帮一下小妹啦!附上完成后的图片

假定需加粗变红的单元格在A列,按钮名称为缺省:CommandButton1。代码如下
Private Sub CommandButton1_Click()
If CommandButton1.Caption = "开启" Then
Application.EnableEvents = True
CommandButton1.Caption = "关闭"
Else
Application.EnableEvents = False
CommandButton1.Caption = "开启"
End If
End Sub

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Target.Column = 1 Then
For i = 3 To Range("A65536").End(xlUp).Row
If Range("A" & i) = Target Then
Range("A" & i).Font.ColorIndex = 3
Range("A" & i).Font.Bold = True
End If
Next i
End If
End Sub
以上代码写在工作表代码区。追问

你好,感谢你 的答案。我还有个疑问,就是怎么才能让命令按钮控制 重复的文字改变。。

追答

不明白你的意思。“重复的文字改变”,怎样改变?

追问

"重复的文字改变"是通过按钮控制,而不是点击了单元格就把文字改变。

追答

为了少改动代码,Targetp 这个单元格对象变量不变,将代码写到按钮(CommandButton2)下,只增加将活动单元给赋给Target即可。
Private Sub CommandButton2_Click()
Set Target = ActiveCell
If Target.Column = 1 Then
For i = 3 To Range("A65536").End(xlUp).Row
If Range("A" & i) = Target Then
Range("A" & i).Font.ColorIndex = 3
Range("A" & i).Font.Bold = True
End If
Next i
End If
End Sub

温馨提示:答案为网友推荐,仅供参考
相似回答