我在当前工作表中有2个命令按钮,两者均已完成,我需要正确的编码

问题描述 投票:0回答:1

我是VBA的新手,所以经验很少。我用基本编码创建了2个命令按钮。 2个命令按钮的原因是字体的颜色。如果单击命令按钮1,则字体将为黑色(在页面上可见且可编辑),如果单击命令按钮2,则在打印报告时,字体将变为白色(不可见)。我已经复制了下面的代码以完成此操作,并且一切正常。当在同一工作簿中复制并移动工作表时,将复制命令按钮,但是当我单击一个按钮时,它会吐出一个错误,并进入代码>基本上,工作表名称需要更改。有人可以帮助我创建一个在复制时自动在所有工作表上运行的代码-我需要大约35个工作表

我的代码是

Sub Changefontcolor()
'this code is the change font color in range of cells
'code start after this line'

Selection.Font.Color = vbRed

End Sub

Private Sub CommandButton1_Click()
'this code is the change front color in rage of cells
'code start after this line'

Worksheets("Audit Template").Range("K76:L92").Select
Selection.Font.Color = vbBlack


End Sub


Private Sub CommandButton2_Click()
'this code is the change front color in rage of cells
'code start after this line'

Worksheets("Audit template").Range("K76:L92").Select
Selection.Font.Color = vbWhite
End Sub
excel vba
1个回答
1
投票

使用控件复制工作表时出现问题

任何工作表代码(Sheet1)

Option Explicit

Private Sub CommandButton1_Click()
    RangeToBlack
End Sub
Private Sub CommandButton2_Click()
    RangeToWhite
End Sub

标准模块(模块1)

Option Explicit

Public Const cRange As String = "K76:L92"

Sub ChangeToRed()
' change font color in any selected range to 'Red'
    Selection.Font.Color = vbRed
End Sub

Sub RangeToBlack()
' change font color in cRange to 'Black'
    ActiveSheet.Range(cRange).Font.Color = vbBlack
End Sub

Sub RangeToWhite()
' change font color in cRange to 'White'
    ActiveSheet.Range(cRange).Font.Color = vbWhite
End Sub

现在,如果您对颜色或范围地址改变主意,则可以在模块中(在一个地方)全部更改。正如SJR所说,您甚至可以删除“ ActiveSheet.”。

© www.soinside.com 2019 - 2024. All rights reserved.