PDA

View Full Version : Return Value from Dialog



Theiks
01-22-2012, 02:25 PM
How can I return a value from a modal form in VBA.

Here is the code I used in VB6:

Begin VB.Form Form2
....
Public sText As String
Private Sub Text1_Change()
sText = Text1.Text
End Sub

VERSION 1.0 CLASS
...
Private m_Text
Public Property Get Text() As String
Text = m_Text
End Property

Sub GetText()
Dim frm As New Form2
frm.Show 1
x = frm.sText
m_Text = frm.sText
End Sub

First question: Why can I set x to frm.sText after frm is closed?
and How do yo do this in VBA?

Thanks.

Jan Karel Pieterse
01-23-2012, 07:13 AM
In VBA it is more or less the same. VBA is just a sub-set of VB6.

Theiks
01-23-2012, 07:30 AM
In VBA it is more or less the same. VBA is just a sub-set of VB6.

Yes, I know.

However in VBA, the reference to frm.sText gives the error that frm does not exist.

I just made a global variable and set it with my dialog, but I would rather not use globals.

Thanks

Kenneth Hobs
01-23-2012, 09:45 AM
If you don't want to use a Public variable, you might want to store the value in a text file or the registry.

In a Module:
Option Explicit

Public sText As String

Sub Test_frm()
frm.Show vbModal
MsgBox sText
End Sub

Sub Test2_frm()
Load frm
frm.TextBox1.Text = "Hobson"
MsgBox frm.TextBox1.Text, vbInformation, "sText = " & sText
Unload frm
End Sub

In the userform named frm:
Option Explicit

Private Sub CommandButton1_Click()
Unload Me
End Sub

Private Sub TextBox1_Change()
sText = TextBox1.Text
End Sub

Theiks
01-24-2012, 07:25 AM
Thanks Ken.

Does anyone know why this works in VB and not VBA?

Jan Karel Pieterse
01-24-2012, 08:45 AM
I'd do it like the atached demo. (check out the module Module1).

Theiks
01-24-2012, 11:16 AM
Thanks Jan. Hide the modal form and close it back at the calling procedure.