首页 > 解决方案 > 当用户单击 Excel 中的特定按钮时,如何编写条件?

问题描述

所以我在 Microsoft Excel 中有这个用户界面,当用户单击一个按钮(在前一个阶段)时会出现这个用户界面,这就是出现的用户界面。 用户界面

如果用户单击按钮,我将无法编写条件。例如,当用户单击按钮时,我想创建一个相关表,然后用相关数据填充表。

我有最后 2 个宏,我只需要用户单击特定按钮时的条件代码。

这是我现在拥有的(这是用户选择 2018-2019 按钮时的代码)

 Option Explicit
        
 Sub Run_All_QB_Macros()

  'shows the userform when user clicks button on main menu

  show_qb_uf

  ' If User clicks 2018-2019 season button then **(THIS IS THE PART I'M HAVING TROUBLE WRITING**)


  ' Create the table for the 2018-2019 season

    qb2018_Create_Table



' Fill out the 2018-2019 season Table with relevant data

  querydatafromMySQL_2018qbs


   End Sub

标签: excelvba

解决方案


您正在将所有代码合二为一Sub。它不像这样工作。

您的用户表单启动代码进入一个单独的过程(可能在一个Module或中Sheet code Area)并且用户表单的点击事件进入Userform code area

这是一个例子

您从模块启动用户窗体

Option Explicit

Sub Run_All_QB_Macros()
    'shows the userform when user clicks button on main menu
    show_qb_uf
End Sub

在此处输入图像描述

现在假设有三个名为的Userform命令按钮CommandButton1,如下所示。CommandButton2CommandButton3

在此处输入图像描述

在用户表单代码区(您可以通过双击访问它Command Button),您需要分别处理每个按钮单击。像这样的东西

Option Explicit

'~~> If User clicks 2018-2019 season button
Private Sub CommandButton1_Click()
    '~~> Create the table for the 2018-2019 season
    qb2018_Create_Table
    
    '~~> Fill out the 2018-2019 season Table with relevant data
    querydatafromMySQL_2018qbs
End Sub

'~~> If User clicks 2019-2020 season button
Private Sub CommandButton2_Click()
    '~~> Create the table for the 2019-202 season
    qb2019_Create_Table
    
    '~~> Fill out the 2019-2020 season Table with relevant data
    querydatafromMySQL_2019qbs
End Sub

'~~> If User clicks 2020-2021 season button
Private Sub CommandButton3_Click()
    '~~> Create the table for the 2020-2021 season
    qb2020_Create_Table
    
    '~~> Fill out the 2020-2021 season Table with relevant data
    querydatafromMySQL_2020qbs
End Sub

在此处输入图像描述

注意:在CommandButton2CommandButton3中,我已经根据您的要求取了样本名称2018-2019。根据需要进行更改。


推荐阅读