VBA 使用用户窗体变量自定义滚动条

VBA Customize scrollbar with UserForm variables

作为 VBA 的新手,我正在尝试向我的 sheet 添加自定义滚动条。通过自定义,我的意思是我可以使用我询问所需值的用户窗体来决定滚动条的最小值、最大值和小变化。到目前为止,我已经将值存储在 public 变量中,如下所示: screen of the Userform

Option Explicit

Public A As Integer
Public B As Integer
Public C As Integer


Private Sub Valider_Click()

If IsNumeric(TextBox1.Value) Then
    A = TextBox1.Value
    Unload Me
Else
    MsgBox "Valeur mimimale incorrecte"
End If

If IsNumeric(TextBox2.Value) Then
    B = TextBox2.Value
    Unload Me
Else
    MsgBox "Valeur maximale incorrecte"
End If

If IsNumeric(TextBox3.Value) Then
    C = TextBox3.Value
    Unload Me
Else 
    MsgBox "Pas incorrect"
End If

MsgBox A & " " & B & " " & C

End Sub

我刚刚重新分配了“.Min”、“.Max”和“.SmallChange”的值。在 Excel :

给出的默认滚动条代码中使用 A、B 和 C
Sub curseur()

ActiveSheet.ScrollBars.Add(180, 45.75, 119.25, 13.5).Select
With Selection
    .Value = 0
    .Min = A
    .Max = B
    .SmallChange = C
    .LargeChange = 10
    .LinkedCell = "$G"
    .Display3DShading = True
End With
Range("F4").Select
ActiveCell.FormulaR1C1 = "=RC[1]/100"
Range("G4").Select
With Selection.Interior
    .Pattern = xlSolid
    .PatternColorIndex = xlAutomatic
    .ThemeColor = xlThemeColorDark1
    .TintAndShade = -0.149998474074526
    .PatternTintAndShade = 0
End With
With Selection.Font
    .ThemeColor = xlThemeColorDark1
    .TintAndShade = -0.149998474074526
End With
End Sub

所以我有 3 个文本框和一个命令按钮 ("Valider")。基本上我的想法是用前面提到的值(最小值、最大值、...)来满足这 3 个框,并将它们存储在 public 变量中。目前,我只是 运行 使用 F5 的开发人员选项卡中的代码。

我是第一个 运行 用户表单。完成文本框并按下命令按钮后,消息框 returns 变量 A、B 和 C 中包含的值。 然后我想将它们用于 "define" 我的滚动条。当我按 F5 键时,滚动条自行显示(见屏幕截图),但如果我转到属性,所有值都设置为零。似乎我没有以正确的方式调用变量 A、B、C:scrollbar properties

在此先感谢您的帮助。

问题是你的第二个子(curseur)不知道你从你的表单中分配了什么值。在代码的最后一位结束后,变量为 'destroyed'。因此 cursur() 中的变量 A、B、C 没有值。

如果您将过程的调用添加到 valider_click 子的末尾,这应该可以解决您的问题。如果您的值不是数字,您应该先退出您的潜艇:

Private Sub Valider_Click()

    If IsNumeric(TextBox1.Value) Then
        A = TextBox1.Value
    Else
        MsgBox "Valeur mimimale incorrecte"
        Exit Sub
    End If

    If IsNumeric(TextBox2.Value) Then
        B = TextBox2.Value
    Else
        MsgBox "Valeur maximale incorrecte"
        Exit Sub
    End If

    If IsNumeric(TextBox3.Value) Then
        C = TextBox3.Value
    Else
        MsgBox "Pas incorrect"
        Exit Sub
    End If

    MsgBox A & " " & B & " " & C
    Call curseur
    Unload Me

End Sub