Search code examples
excelvbaemailradio-buttonuserform

Return Userform Option button value to email body


I have a userform I want to give information to populate the body of an Outlook email.

I've been able to get the result with Comboboxes for Yes/No answers, but not for option buttons.

With the combobox yes/no dropdown I've been defining a variable based off the answer and then using it in the body of the Outlook email by referencing the variable with an &.

Option button sub:

Private Sub GetAnswer()
Dim OBAnswer As String
If OBYes.Value = True Then OBAnswer = "Yes"
ElseIf OBNo.Value = True Then OBAnswer = "No"
End If
End Sub

In my email sub, when I try:
emailitem.Body = "The answer is " & OBAnswer

I get a Compile error:

Variable no defined.

I tried defining OBAnswer as a variant or using OBAnswer.Text in the email body code.


Solution

  • Change your Sub to Function, and call that function to get your answer.

    Private Function GetAnswer() as String
        
        If OBYes.Value = True Then GetAnswer = "Yes"
        ElseIf OBNo.Value = True Then GetAnswer = "No"
        End If
    
    End Function
    
    '// ...
    emailitem.Body = "The answer is " & GetAnswer()
    '// ...
    

    Otherwise, if you need to store the answer ahead of time, just declare a public variable to hold the string outside of the GetAnswer method and reference that.