显示选择按钮多少次的逻辑

时间:2019-04-11 19:18:12

标签: excel vba

Question and buttons我目前正在使用excel-vba,并且试图创建一个简单的问答。到目前为止,我的Excel工作表中有一个问题可以回答上述问题。我有四个按钮,当您选择每个按钮时,都会出现一条消息。我想知道是否可以为每个按钮添加一些逻辑以显示选择按钮的次数以及该问题的回答次数?

我曾尝试对此进行研究,但是大多数答案都显示在Java和android编程中。没有excel-vba。

Sub Tomatoes()


MsgBox "Correct"
End Sub

Sub Cucumbers()

MsgBox "Wrong Answer, that would be too healthy, Please choose again."
End Sub

Sub Lime()

MsgBox "Incorrect Answer, that ketchup would be exteremely sour."
End Sub

Sub Apples()

MsgBox "Incorrect, Apples with Ketchup would be horrible. "
End Sub

创建每个按钮,以便在选择该按钮时将显示不同的选项。有没有一种方法可以向每个按钮添加逻辑以显示选择了多少次?并添加逻辑以显示该问题得到了多少次回答?

2 个答案:

答案 0 :(得分:2)

您正在使用窗体控件,其优点是可以将所有控件都指向同一个Sub。因此,像这样创建一个新的子并将所有按钮都指向此。此子项将适当地增加Sheet2上的计数器。这是Sheet2的外观:

spark-streaming-kafka-0-10_2.11

Sub btnIngredient_Click()

    Dim wb As Workbook
    Dim wsQuestion As Worksheet
    Dim wsCounts As Worksheet
    Dim rDest As Range

    Set wb = ActiveWorkbook
    Set wsQuestion = wb.ActiveSheet
    Set wsCounts = wb.Worksheets("Sheet2")

    Select Case wsQuestion.Shapes(Application.Caller).TextFrame.Characters.Text
        Case "Cucumbers":   Set rDest = wsCounts.Range("B3")
                            MsgBox "Wrong Answer, that would be too healthy, Please choose again."

        Case "Tomatoes":    Set rDest = wsCounts.Range("B4")
                            MsgBox "Correct"

        Case "Lime":        Set rDest = wsCounts.Range("B5")
                            MsgBox "Incorrect Answer, that ketchup would be exteremely sour."

        Case "Apples":      Set rDest = wsCounts.Range("B6")
                            MsgBox "Incorrect, Apples with Ketchup would be horrible. "

    End Select

    wsCounts.Range("B2").Value = wsCounts.Range("B2").Value + 1 'Increase counter of the total times question answered
    rDest.Value = rDest.Value + 1   'Increase counter of individual button clicked

End Sub

要清除工作簿关闭时的计数器,请使用Workbook_BeforeClose事件(确保此代码位于ThisWorkbook代码模块中):

Private Sub Workbook_BeforeClose(Cancel As Boolean)

    Me.Worksheets("Sheet2").Range("B2:B6").Value = 0

End Sub

答案 1 :(得分:1)

每个按钮的Sub可以跟踪您所需的信息。通过添加一些模块级变量,您的代码可能类似于以下内容:

Private CucumbersPressed As Integer
Private TomatoesPressed As Integer
Private QuestionAnswered As Integer

Private Sub Cucumbers()
   CucumbersPressed = CucumbersPressed + 1
   QuestionAnswered = QuestionAnswered + 1

   MsgBox "Wrong"
End Sub

Private Sub Tomatoes()
   TomatoesPressed = TomatoesPressed + 1
   QuestionAnswered = QuestionAnswered + 1

   MsgBox "Correct"
End Sub

根据问题的数量和按钮的数量,此方法可能变得笨拙。在那种情况下,可能需要其他机制,但想法会类似。