【问题标题】:Microsoft Excel :: Checkbox MacroMicrosoft Excel :: 复选框宏
【发布时间】:2019-09-24 21:50:56
【问题描述】:
我想要这样当我选中第 1 项的框时,文本会出现在它旁边。我已经为此编写了一个简单的宏。问题是,我希望在未选中该框时文本消失。我有它,这样当您选中该框时,文本就会出现。如果您取消选中该框,则文本 不会 消失,而我希望它消失。
所以基本上,我想做的就是在我选中该框时显示文本,而当我取消选中它时文本消失。我怎样才能做到这一点。
Sub CheckBox1_Click()
'
' CheckBox1_Click Macro
'
'
Range("E2").Select
ActiveCell.FormulaR1C1 = "Puppy Tears"
Range("E3").Select
ActiveCell.FormulaR1C1 = "Tuna"
Range("E4").Select
End Sub
【问题讨论】:
标签:
excel
checkbox
excel-2010
【解决方案1】:
您需要检查复选框的值并使用if 语句来打开/关闭。
如果您使用了“表单控件”复选框,则可以使用以下示例:
Sub Checkbox1_Click()
Dim Sheet As Worksheet: Set Sheet = ThisWorkbook.Worksheets("Sheet1")
If Sheet.Shapes("Check box 1").OLEFormat.Object.Value = 1 Then
' checkbox is checked
Else
' checkbox is not checked
End If
End Sub
手动更改形状的名称(我认为,从未真正研究过)相当棘手,但您可以使用以下宏来添加复选框,它包含一个宏来处理复选框的所有事件
' this code should be added in a new module (menu->insert->module)
Sub AddCheck()
' this sub will add a new checkbox to sheet1 in the active cell. you specify the name, and the name will be duplicated in the caption
Dim Name As String: Name = InputBox("Shape Name")
Dim Shape As Shape
Dim Sheet As Worksheet: Set Sheet = ThisWorkbook.Worksheets("Sheet1")
Dim PTop As Integer
Dim PLeft As Integer
PTop = ActiveCell.Top
PLeft = ActiveCell.Left
Set Shape = Sheet.Shapes.AddFormControl(xlCheckBox, PLeft, PTop, 100, 10)
Shape.Name = Name
Shape.OLEFormat.Object.Caption = Name
Shape.OLEFormat.Object.Value = 0
Shape.OnAction = "Checkbox_Click"
End Sub
Sub Checkbox_Click()
' this is a generic function that will be fired by all checkboxes added using the above macro
Dim Sheet As Worksheet: Set Sheet = ThisWorkbook.Worksheets("Sheet1")
' copy and edit the following if statement for all checkboxes
If Sheet.Shapes("Check1").OLEFormat.Object.Value = 1 Then
' its checked
Else
' its not checked
End If
End Sub
如果您使用过“ActiveX 控件”,那么我真的帮不上忙,因为 Excel 目前不允许我添加。
【解决方案2】:
Private Sub CheckBox1_Click()
Dim i As Integer
i = 1
Do While CheckBox1.Value = True And i < 3
Range("D1").Value = "Puppy tears"
Range("D2").Value = "Tuna"
i = i + 1
Loop
Do While CheckBox1 = False And i < 3
Range("D1").Value = ""
Range("D2").Value = ""
i = i + 1
Loop
End Sub
我想这会对你有所帮助(你应该使用 ActiveX 控件,否则它不会进入第一个循环。)