0

我几乎是 Excel VBA 的新手。我试图在 UserForm2 上的工作表中显示某些单元格的值,并在用户单击 CommandButton1 时卸载表单。为了避免为我的控件构建一个类,我从一个草稿用户窗体开始,我需要的所有组件都放在上面。我设置文本框的位置,填写它们,设置CommandButton1的位置。这些都很好,都按预期/计划显示。当我单击表单上的 CommandButton1 时,我听到“叮”声,并且未显示“单击的 CB1”消息(我希望看到)。我做错了什么或缺少什么?

Option Explicit
Public leftOfForm As Long
Public topOfForm As Long
Public widthOfForm As Long
Public heightOfForm As Long
' ***********************************
Dim numInfoMessages  As Long
Dim heightBox As Long
Dim lengthTextbox As Long
Dim lengthCommandButton As Long
Dim numberOfScreenRows As Long
Dim horizantalPadding As Long
Dim verticalPadding As Long
Dim indexLoop As Integer
Dim contr As Control
Dim theFontSize As Integer

Public Sub CommandButton1_Click()
'
'   Just to confirm it is ok --- current userform will be unloaded
'
    MsgBox "clicked CB1"
End Sub

Public Sub UserForm_initialize()
'
'   Save forms current info - not needed in fact
'
    theFontSize = 12
    leftOfForm = UserForm2.Left
    topOfForm = UserForm2.top
    widthOfForm = UserForm2.Width
    heightOfForm = UserForm2.Height
    numInfoMessages = 6
'
'  Calculate userform size based on number of lines to be displayed
'
    heightBox = 25
    lengthTextbox = 500
    lengthCommandButton = 90
    verticalPadding = 20
    horizantalPadding = 15
    numberOfScreenRows = (numInfoMessages + 1) * 2 + 1
'
'   Resize form according to the results
'
    UserForm2.Width = horizantalPadding * 3 + lengthTextbox + 10
    UserForm2.Height = verticalPadding * (numberOfScreenRows + 2)
    UserForm2.top = 0
    UserForm2.Left = 0             
'
'   Fill in and allocate the text boxes
'
    indexLoop = 1
    For Each contr In UserForm2.Controls
        If TypeName(contr) = "TextBox" Then
            contr.top = (indexLoop) * 2 * verticalPadding
            contr.Left = horizantalPadding
            contr.Width = lengthTextbox
            contr.Height = heightBox
            contr.BorderStyle = 1
            contr.Text = ThisWorkbook.Worksheets(ThisWorkbook.messagesPageName).Range("B" & indexLoop + 1).Value
            contr.WordWrap = False
            contr.MultiLine = False
            contr.Font.Size = theFontSize
            indexLoop = 1 + indexLoop
        End If
    Next
'
'   Allocate the command button
'
    For Each contr In UserForm2.Controls
        If TypeName(contr) = "CommandButton" Then
            contr.top = (indexLoop) * 2 * verticalPadding
            contr.Width = lengthCommandButton
            contr.Height = heightBox
            contr.Width = lengthCommandButton
            contr.Left = UserForm2.Width / 2 - contr.Width / 2
            contr.top = (indexLoop) * 2 * verticalPadding
            contr.Font.Size = theFontSize
        End If
    Next
End Sub
4

0 回答 0