问题
Let me start off by stating that I am a medical student, not a programmer. I have written a spreadsheet that will work as an exam with 50 questions. Each question has 15 multiple choice answers for which I use ActiveX Option Buttons grouped to each question number.
I use Activex instead of Form Option Button because I dump raw data from an exam into a hidden area of the worksheet and each option button caption references a cell in the raw data to display a different answer choice. This way I can easily create a new exam just by adding a table of questions and answer choices. I don't see how to do this with form option button.
But the ActiveX option buttons can't seem to return an index value to a single cell. So, I have written the following for each button:
Sub OptionButton1_Click()
Range("B21") = "A"
End Sub
Sub OptionButton2_Click()
Range("B21") = "B"
End Sub
Sub OptionButton3_Click()
Range("B21") = "C"
End Sub
... and so on. Fifteen buttons per question. Fifty questions. My worksheet is terribly slow to load and crashes on slower computers all the time. There has to be an easier way. Any suggestions? Ideally, I would like a small snippet of code that could return an index value from each group to a particular cell whenever any option button in that group is selected. Any help would be greatly appreciated.
On the other hand... another piece of help that would basically get me there would be if someone could help me figure out how to change the caption of a form option button to reference a given cell. That would ALSO solve my problem.
回答1:
The way to create a group event is to have a custom class to wrap the controls that you want to group and a module level collection to keep the wrapper class references alive.
After reviewing your workbook I determined that you can derive an index based on the OptionButton's Name.
Class: OptionWrapper
Option Explicit
Public WithEvents MyOptionButton As MSForms.OptionButton
Private Sub MyOptionButton_Click()
Dim Letters()
Dim lRow As Long, lAnswer As Long, ID As Long
Letters = Array("O", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N")
ID = Replace(MyOptionButton.Name, "OptionButton", "")
lRow = Int(ID / 15 + 1) * 21
lAnswer = ID Mod 15
Cells(lRow, "B") = Letters(lAnswer)
End Sub
Exam Worksheet Code Module
Private OptionsCollection As Collection
Private Sub Worksheet_Activate()
Dim obj As OLEObject
Dim wrap As OptionWrapper
Set OptionsCollection = New Collection
For Each obj In ActiveSheet.OLEObjects
If TypeOf obj.Object Is MSForms.OptionButton Then
Set wrap = New OptionWrapper
Set wrap.MyOptionButton = obj.Object
OptionsCollection.Add wrap
End If
Next
End Sub
来源:https://stackoverflow.com/questions/39896458/returning-an-index-value-from-a-group-of-activex-option-buttons