无法在Excel VBA中运行CommandButton1_Click

时间:2019-02-05 15:04:32

标签: excel vba

我几乎是Excel VBA的新手。 我试图在UserForm2上显示工作表中某些单元格的值,并在用户单击CommandButton1时卸载表单。 为了避免为控件构建类,我从一个UserForm草稿开始,将需要的所有组件都放在该草稿上。 我设置文本框的位置,填写它们,然后设置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

0 个答案:

没有答案