vb和vba还是有区别的,尽管他们的语法大致相同。
1应该是控件编号,如果是手动画控件,第一个的编号默认为1
至于为添加的控件添加代码,百度有很多
’将程式码复制到Module中,然後执行 GetOption程序
Sub GetOption()
Dim TempForm 'As VBComponent
Dim NewOptionButton As MSForms.OptionButton
Dim LeftPos As Integer
Dim X As Integer, i As Integer, TopPos As Integer
' 隐藏VBE视窗预防萤幕更新
Application.VBE.MainWindow.Visible = False
' 动态新增UserForm
Set TempForm = ActiveWorkbook.VBProject.VBComponents.Add(3)
' 新增 OptionButtons
LeftPos = 4
k = 1
TopPos = 5
For i = 1 To 3
LeftPos = 4
For j = 1 To 10
'动态新增OptionButton控件
Set NewOptionButton = _
TempForm.Designer.Controls.Add("forms.OptionButton.1")
With NewOptionButton
.Width = 60
.Caption = k & "℃"
.Height = 15
.Left = LeftPos
.Top = TopPos
.Tag = k & "℃"
.AutoSize = True
End With
LeftPos = LeftPos + 30
k = k + 1
Next j
TopPos = i * 20 + 5
Next i
'【写入Click 事件】
For i = 1 To 30
With TempForm.CodeModule
X = .CountOfLines
.InsertLines X + 1, "Private Sub OptionButton" & i & "_Click()"
.InsertLines X + 2, " Cells(8, 8) = Me.ActiveControl.Tag"
.InsertLines X + 3, "End Sub"
End With
Next i
With TempForm
.Properties("Caption") = "温度选项"
.Properties("Width") = LeftPos + 20
.Properties("Height") = TopPos + 20
.Properties("Left") = 160
.Properties("Top") = 150
End With
'显示窗体
VBA.UserForms.Add(TempForm.Name).Show
'关闭後一橱窗体
ActiveWorkbook.VBProject.VBComponents.Remove VBComponent:=TempForm
End Sub
希望楼主耐心揣摩,举一反三Sub 建立窗体并运行()
Dim TempForm As Object '采用后期绑定
Application.VBE.MainWindow.Visible = False '防止窗口闪动
Set TempForm = ThisWorkbook.VBProject.VBComponents.Add(3) ' 建立窗体
With TempForm
.Properties("Caption") = "智能输入"
.Properties("Width") = 100
.Properties("Height") = 100
End With
With TempForm.Designer.Controls.Add("forms.ComboBox.1") '创建组合框
.Left = 10
.Top = 15
End With
With TempForm.Designer.Controls.Add("forms.CommandButton.1") '创建一个按钮
.Left = 10
.Top = 45
.Caption = "输入当前日期"
End With
With TempForm.CodeModule ' 为窗体添加代码
.InsertLines .CountOfLines + 1, "Private Sub UserForm_Activate()"
.InsertLines .CountOfLines + 2, "Me.ComboBox1.List = Array(""一月"", ""二月"", ""三月"", ""四月"", ""五月"", ""六月"", ""七月"", ""八月"", ""九月"", ""十月"", ""十一月"", ""十二月"")"
.InsertLines .CountOfLines + 3, "Me.ComboBox1 = WorksheetFunction.Text(VBA.Month(Date), ""[DBNum1][$-804]0月"")"
.InsertLines .CountOfLines + 4, "End Sub"
.InsertLines .CountOfLines + 5, "Private Sub ComboBox1_Change()"
.InsertLines .CountOfLines + 6, "If TypeName(ActiveCell) = ""Range"" Then ActiveCell = Me.ComboBox1.Text"
.InsertLines .CountOfLines + 7, "End Sub"
.InsertLines .CountOfLines + 8, "Private Sub CommandButton1_Click()"
.InsertLines .CountOfLines + 9, "If TypeName(ActiveCell) = ""Range"" Then ActiveCell = date"
.InsertLines .CountOfLines + 10, "End Sub"
End With
VBA.UserForms.Add(TempForm.Name).Show ' 显示窗体
ThisWorkbook.VBProject.VBComponents.Remove TempForm ' 运行完毕删除窗体
End Sub
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)