Return 标签标题和相应的选项按钮标题作为列表

Return Label caption and corresponding option button caption as list

我正在使用 Excel VBA 用户表单,其中的问题动态显示为标签标题,所有显示的问题旁边都有一个 Yes/No 选项按钮组。

我正在尝试 return 标签的标题和所选答案,但 excel 似乎是随机选择通过选项按钮。

我有的是:

我想要的是一个文本输出,然后我可以将其复制到电子邮件中,如下所示:

奇怪的是,有时最后一道题的顺序会调换。 (我什至更改了选项卡索引,但这没有帮助)。

我在这里错过了什么?

感谢您的帮助。

标签被称为Label1、Label2、Label3等。 选项按钮称为 Optbtn1y、Optbtn1n、Optbtn2y、Optbtn2n、Optbtn3y、Optbtn3n 等

Private Sub returnoptbttnv()
 
'determine name and caption of all enabled OptionButtons in a Frame
 
Dim ctrl As Control
Dim Lbel As Control
Dim txt1 As String
Dim txt2 As String
txt1 = ""
txt2 = ""
 
For Each Lbel In Frame2.Controls
    If TypeName(Lbel) = "Label" And Lbel.Visible = True Then
    txt1 = Lbel.Caption
    End If
Next Lbel
    
For Each ctrl In Frame2.Controls
    If TypeOf ctrl Is MSForms.OptionButton Then
    If ctrl.Value = True And ctrl.Visible = True Then
    txt2 = ctrl.Caption
    End If
    End If
Next ctrl
    MsgBox (txt1 & txt2)
End Sub

对于任何特定的可见标签,你可以得到它的Name,从中你可以得到相应的“是”和“否”选项按钮的名称,并直接检查它们的状态。

Private Sub returnoptbttnv()
 
    'determine name and caption of all enabled OptionButtons in a Frame
    Dim ctrl As Control
    Dim Lbel As Control
    Dim txt1 As String, optBase As String, y As Boolean, n As Boolean
    
    For Each Lbel In Me.Frame2.Controls
        If TypeName(Lbel) = "Label" And Lbel.Visible Then
            
            optBase = Replace(Lbel.Name, "Label", "Optbtn") 'option button "base name"
            y = Me.Frame2.Controls(optBase & "y").Value
            n = Me.Frame2.Controls(optBase & "n").Value
            txt 1 = txt1 & Lbel.Caption & " ------ " & _
                    IIf(y, "Yes", IIf(n, "No", "")) & Chr(10)
        End If
    Next Lbel
    
    MsgBox txt1
End Sub

您的要求似乎是 return 所有问题和答案的列表。我采取了一种不同的方法,不遍历控件集合:

Private Function GetAnswers() As String
   On Error Resume Next

   Dim i As Integer
   Dim question As MSForms.Label
   Dim answer As MSForms.OptionButton
   
   GetAnswers = ""
   
   i = 0
   
   Do
      i = i + 1
      Set question = Nothing
      Set question = Me.Frame2.Controls("Label" & i)
      
      If question Is Nothing Then Exit Do
      
      If question.Visible Then
         Set answer = Me.Frame2.Controls("Optbtn" & i & "Y")
         If Not answer.Value Then Set answer = Me.Frame2.Controls("Optbtn" & i & "N")
         GetAnswers = GetAnswers & question.Caption & " - " & answer.Caption & vbCrLf
      End If
   Loop
End Function