excel表格的基本操作-excel教程网移动版

主页 > 高级教程 > vba >

Excel VBA经典应用案例(设计按钮)

设计按钮
Sub RunTimeButton()
' Adds a button at runtime

' Make sure access to the VBProject is allowed
  On Error Resume Next
  Set x = ActiveWorkbook.VBProject
  If Err <> 0 Then
    MsgBox "Your security settings do not allow this macro to run.", vbCritical
    On Error GoTo 0
    Exit Sub
  End If

  Dim Butn As CommandButton
  Set Butn = UserForm1.Controls.Add("Forms.CommandButton.1")
  With Butn
    .Caption = "Added at runtime"
    .Width = 100
    .Top = 10
  End With
  UserForm1.Show
End Sub

Sub DesignTimeButton()
' Adds a button at design-time

' Make sure access to the VBProject is allowed
  On Error Resume Next
  Set x = ActiveWorkbook.VBProject
  If Err <> 0 Then
    MsgBox "Your security settings do not allow this macro to run.", vbCritical
    On Error GoTo 0
    Exit Sub
  End If

  Dim Butn As CommandButton
  Set Butn = ThisWorkbook.VBProject.VBComponents("UserForm1") _
    .Designer.Controls.Add("Forms.CommandButton.1")
  With Butn
    .Caption = "Added at design-time"
    .Width = 120
    .Top = 40
  End With
  VBA.UserForms.Add("UserForm1").Show
End Sub
(责任编辑:admin)