[英]Macro Excel: Assign macro to Userform
我有一个编码来计算x和y模具的数量(实际上是列和行)。 如何将编码插入UserForm以使其起作用? 然后,在为每个x和y模具输入数据并按“确定”后,我希望输出显示在我的工作表上。 我对“确定”部分使用什么编码? 对于“取消”部分也是如此。 我还是VBA代码的新手。
我的代码:
Sub InsertShapeRange()
Dim my_row As Integer
Dim my_col As Integer
Dim Rng As Range
Dim shp As Shape
Dim ws As Worksheet
my_col = Application.InputBox("No. of x dies?", "Wafer Map", Default:=0)
my_row = Application.InputBox("No. of y dies?", "Wafer Map", Default:=0)
Set Rng = Selection
Set Rng = Rng.Resize(my_row, my_col)
Set ws = Rng.Parent
Set shp = ws.Shapes.AddShape(1, Rng.Left, Rng.Top, Rng.Width, Rng.Height)
With shp
.Fill.Visible = msoFalse
With .Line
.Visible = msoTrue
.ForeColor.RGB = RGB(0, 0, 0)
.Transparency = 0
End With
End With
With Rng
.Borders(xlInsideHorizontal).LineStyle = xlContinuous
.Borders(xlInsideVertical).LineStyle = xlContinuous
End With
End Sub
我有一个用户窗体,如下所示。
您可以在子程序中添加参数。
Sub InsertShapeRange(my_col As Integer, my_row As Integer)
然后,您需要删除这些行,因为变量现在在Sub定义中定义:
Dim my_row As Integer
Dim my_col As Integer
my_col = Application.InputBox("No. of x dies?", "Wafer Map", Default:=0)
my_row = Application.InputBox("No. of y dies?", "Wafer Map", Default:=0)
现在,通过右键单击按钮并选择查看代码,为单击确定按钮添加代码。
Private Sub cmdOK_Click()
InsertShapeRange txtXDies, txtYDies
Me.Hide
End Sub
您可能还希望将“确定”按钮的“默认”属性设置为True,以便按Enter键与单击它相同。 确保取消属性设置为False。
对于“取消”按钮,输入以下代码以隐藏表单。
Private Sub cmdCancel_Click()
Me.Hide
End Sub
最后像这样将“取消”按钮的“取消”属性设置为“真”。 这使得按Escape键等效于单击它。 还将默认设置为False。
完整的“表单代码”模块将如下所示:
Option Explicit
Private Sub cmdCancel_Click()
Me.Hide
End Sub
Private Sub cmdOK_Click()
InsertShapeRange txtXDies, txtYDies
Me.Hide
End Sub
现在,已完成的InsertShapeRange子例程将如下所示。
Sub InsertShapeRange(my_col As Integer, my_row As Integer)
Dim Rng As Range
Dim shp As Shape
Dim ws As Worksheet
Set Rng = Selection
Set Rng = Rng.Resize(my_row, my_col)
Set ws = Rng.Parent
Set shp = ws.Shapes.AddShape(msoShapeRectangle, Rng.Left, Rng.Top, Rng.Width, Rng.Height)
With shp
.Fill.Visible = msoFalse
With .Line
.Visible = msoTrue
.ForeColor.RGB = RGB(0, 0, 0)
.Transparency = 0
End With
End With
With Rng
.Borders(xlInsideHorizontal).LineStyle = xlContinuous
.Borders(xlInsideVertical).LineStyle = xlContinuous
End With
End Sub
在我的示例中,文本框的名称为“ txtXDies”和“ txtYDies”,“确定”按钮为“ cmdOK”,而取消按钮为“ cmdCancel”。 您可以检查名称或在“属性”窗口中重命名它们-按F4并单击对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.