[英]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.