我在excel中有待办事项列表。选中复选框后,将运行一个宏,用于选择特定单元格并将值添加到该单元格的偏移量。问题是我有600个复选框,他们都需要自己的代码来引用正确的单元格。
private sub checkbox1_click ()
Range ("I2").offset(0,3).value= "hello world"
Sub end
我想要这样的事情:
Range ("location of checkbox I just checked").offset(0,3).value= "hello world"
答案 0 :(得分:3)
如果使用ActiveX控件复选框而不是表单控件,这将更容易。
使用ActiveX控件复选框,您可以将对象引用为Me
的一部分,它指向工作表本身并使用以下内容:
Private Sub CheckBox1_Click()
If Me.CheckBox1.Value = True Then
Me.CheckBox1.TopLeftCell.Offset(0, 3).Value = "hello world"
End If
End Sub
如果您无法使用ActiveX控件,请告诉我,我可以调整我的答案。请注意,您还可以查看有关如何通过查看this question的答案来使复选框引用自身的更多信息。
在PeterT的回答中,您还可以看到如何使用类模块来避免每个复选框都有一个宏的问题。在这里,我复制了答案的相关部分:
[...]创建一个可以为任意数量的实例化的类模块 的复选框。
类模块MyCheckBoxClass的代码
Dim WithEvents cbControl As MSForms.CheckBox Private controlName As String Public Sub cbControl_Click() Debug.Print controlName & " is now " & cbControl.Value If cbControl.Value = True Then Range("CheckBoxCount") = Range("CheckBoxCount") + 1 'choose to store on the sheet groupCheckBoxCount = groupCheckBoxCount + 1 'or in a variable Else Range("CheckBoxCount") = Range("CheckBoxCount") - 1 groupCheckBoxCount = groupCheckBoxCount - 1 End If End Sub Public Sub Attach(newCB As MSForms.CheckBox, newName As String) Set cbControl = newCB controlName = newName End Sub Private Sub Class_Initialize() controlName = "" End Sub
常规代码模块中的代码:
Public groupClickCount As Integer Private cbCollection As Collection Public Sub SetUpControlsOnce() Dim thisCB As MyCheckBoxClass Dim ctl As OLEObject Dim cbControl As MSForms.CheckBox If cbCollection Is Nothing Then Set cbCollection = New Collection End If For Each ctl In ThisWorkbook.Sheets("Sheet1").OLEObjects If TypeName(ctl.Object) = "CheckBox" Then '--- this is an ActiveX CheckBox Set thisCB = New MyCheckBoxClass thisCB.Attach ctl.Object, ctl.name cbCollection.Add thisCB End If Next ctl End Sub
当然,您必须更换" Sheet1"使用适当的工作表名称和
If cbControl.Value = True Then
Range("CheckBoxCount") = Range("CheckBoxCount") + 1 'choose to store on the sheet
groupCheckBoxCount = groupCheckBoxCount + 1 'or in a variable
Else
Range("CheckBoxCount") = Range("CheckBoxCount") - 1
groupCheckBoxCount = groupCheckBoxCount - 1
End If
。通过强>
If cbControl.Value = True Then
cbControl.TopLeftCell.Offset(0, 3).Value = "hello world"
End If
最后,我建议在打开工作簿时运行SetUpControlsOnce
宏,方法是将其包含在工作簿对象的Open事件中(Thisworkbook)。即:
Private Sub Workbook_Open()
Call SetUpControlsOnce
End Sub