VBA使用单击的按钮名称

时间:2018-08-30 07:29:55

标签: excel vba excel-vba

在我的工作簿中,我有两个工作表(“概述”和“ Assignment_Data”)。在第一张纸上,我有五个具有不同名称的ActiveX按钮(“ WKA” /“ WKS” /“ GM” /“ IBN” /“ PM”)

每个按钮打开用户窗体“ Add_Assignment”,该窗体还有两个按钮(“保存”和“取消”)。 UF的数据应保存在“ Assignment_Data”工作表中。

现在我想如果我单击例如WKA按钮,则数据应保存在范围A:C中;范围E:G中的按钮WKS。另外,按钮名称应在第1行中用作标题。

不幸的是,我不知道该怎么做。

按钮:

Private Sub WKA_Click()
    Add_Assignment.Show
End Sub

Private Sub WKS_Click()
    Add_Assignment.Show
End Sub

Private Sub GM_Click()
    Add_Assignment.Show
End Sub

Private Sub IBN_Click()
    Add_Assignment.Show
End Sub

Private Sub PM_Click()
    Add_Assignment.Show
End Sub

用户窗体:

Private Sub Save_Click()
    Dim ws As Worksheet
    Dim Col1 As Integer, Col2 As Integer, Col3 As Integer

    Set ws = Worksheets("Assignment_Data")
    If "ButtonName" = "WKA" Then
        Col1 = "A"
        Col2 = "B"
        Col3 = "C"
    ElseIf "ButtonName" = WKS Then
        Col1 = "E"
        Col2 = "F"
        Col3 = "G"
    ElseIf ' goes on till PM

    End If

    ws.Range(Col1 & "2").Value = Add_Assignment.Controls("TextBox1")
    ws.Range(Col2 & "2").Value = Add_Assignment.Controls("TextBox2")
    ws.Range(Col3 & "2").Value = Add_Assignment.Controls("TextBox3")
    ws.Range(Col1 & "3").Value = Add_Assignment.Controls("TextBox4")
    ws.Range(Col2 & "3").Value = Add_Assignment.Controls("TextBox5")
   ' and so on

    Add_Assignment.Hide
End Sub

Private Sub Cancel_Click()
    Add_Assignment.Hide
End Sub

编辑:

带有Application.Caller的代码:

Private Sub Save_Click()
    Dim ws As Worksheet
    Dim Col1 As Integer, Col2 As Integer, Col3 As Integer
    Dim name As String

    name = ActiveSheet.Shapes(Application.Caller).name ' in this line i get the error

    Set ws = Worksheets("Assignment_Data")
    If name = "WKA" Then
        Col1 = "A"
        Col2 = "B"
        Col3 = "C"
    ' ...
    End If

    ' Do something

End Sub

1 个答案:

答案 0 :(得分:0)

是否需要使用表格?听起来这可以通过简单的MsgBox来实现:

Sub confirmSave(btn_name As String)
    Dim res As VbMsgBoxResult
    res = MsgBox("Save?", buttons:=vbOKCancel)
    If res = VbOK Then ...
End Sub

,然后将要复制的值放在单独的工作表中。所以不要做

ws.Range(Col1 & "2").Value = Add_Assignment.Controls("TextBox1")
ws.Range(Col2 & "2").Value = Add_Assignment.Controls("TextBox2")
...

您只需要

ws.Range(StartCol & "2:" & EndCol & "3").Value = TemplateSheet.Range("A2:C3").Value ' or wherever the range is