从表单按钮调用子

时间:2018-11-12 16:30:17

标签: excel vba

我正在尝试通过用户表单按钮从当前工作表中调用一个子项,但出现以下错误; “编译错误:未定义子函数或子函数”。

这是代码

Private Sub form_addDate_clickSubmit_Click()
    Dim WKB As Workbook
    Dim SHT_EDIT As Worksheet
    Set WKB = ActiveWorkbook
    Set SHT_EDIT = WKB.Sheets("EDIT")
    Call loadData
    'Tried various other ways such as SHT_EDIT.loadData
End Sub

loadData子项是公共的。

谢谢

2 个答案:

答案 0 :(得分:0)

您的子loadData可能在工作表模块中。

您可以使用[SHT_EDIT].loadData来调用它,假设工作表的 CodeName SHT_EDIT(代码名称是VBA Project Explorer中显示的名称,而不是Excel中工作表的名称。

更好的解决方案是将Sub移到常规模块中。

答案 1 :(得分:0)

这是我在工作表上编写命令按钮的方式:

Option Explicit
Public WS As Worksheet     ' global Worksheet object

Private Sub InsertNextWeek_Button1_Click()
'Button to call the Insert Next Week subprocedure

  'Save the current active worksheet
  Set WS = ThisWorkbook.ActiveSheet

  'Run procedure to Insert 7 new rows for Next Week
  Call Insert_NextWeek

  'Make this worksheet is left as the active worksheet
  WS.Activate

  'clear worksheet variable
  Set WS = Nothing
End Sub

Private Sub PublishRunStats_Button6_Click()
'Button to call the Publish RunStats subprocedure

  'Save the current active worksheet
  Set WS = ThisWorkbook.ActiveSheet

  'Run procedure to Save the Run Stats worksheet to a new workbook
  Call Publish_RunStats_Sheet

  'Make this worksheet is left as the active worksheet
  WS.Activate

  'clear worksheet variable
  Set WS = Nothing
End Sub

被调用的子过程在同一工作簿的Module1中编码为Public。
在每个命令按钮子过程中都使用全局WS对象,以确保我的显示焦点最终回到与单击命令按钮相同的工作表上。