类似的多个对象的语法

我在我的用户表单上有多个旋钮,我想把相同的代码放在每一个上,

Me.TextBox1.Value = Me.TextBox1.Value - 1 If Me.TextBox1.Value = 0 Then Me.TextBox1.Value = 12 End If If Me.TextBox1.Value < 10 Then Me.TextBox1.Value = "0" & Me.TextBox1.Value End If 

但是有没有简单的方法,而不是把多个块放在多个旋钮上,并把它们全部组合在一起?

将大量的代码放到它自己的Sub过程中,并从每个button的“处理器”子对象传递给它。

 Private Sub button1_Click() allSpin Me.TextBox1 End Sub Private Sub button2_Click() allSpin Me.TextBox2 End Sub Private Sub button3_Click() allSpin Me.TextBox3 End Sub Sub allSpin(ByRef tb As Object) With tb .Value = .Value - 1 If .Value = 0 Then .Value = 12 ElseIf .Value < 10 Then .Value = "0" & .Value End If End With End Sub 

这是相当普遍和tbh,我怀疑它是否会直接开箱即用,但我希望它是足以给你一个想法如何工作。

最后一个子可能会更好,

 Sub allSpin(ByRef tb As Object) With tb If Int(.Value) = 1 Then .Value = 12 Else .Value = Format(Int(.Value) - 1, "00") End If End With End Sub 

您的代码将Textbox.value引用为整数。 我认为你可能想要做的是让旋转button从0到12,当点击时,也许停在12点击。 假设SpinButtons是SpinButton1,SpinButton2,SpinButton3,并且有相同数字的相关文本框:试试这个

 Private Sub SpinButton1_Change() SpinUpdate End Sub Private Sub SpinButton2_Change() SpinUpdate End Sub Private Sub SpinButton3_Change() SpinUpdate End Sub Private Sub SpinUpdate() Dim StrI As String StrI = Right(ActiveControl.Name, 1) With Me.Controls("SpinButton" & StrI) If .Value = 0 Then .Value = 12 End If Me.Controls("TextBox" & StrI).Text = Format(.Value, "00") End With End Sub Private Sub UserForm_Click() Dim i As Integer For i = 1 To 3 With Me.Controls("SpinButton" & Format(i)) .Min = 0 .Max = 12 End With Next i End Sub 
    Interesting Posts