Home > Back-end >  Passing text box text from a userform to a sheet using MVP pattern
Passing text box text from a userform to a sheet using MVP pattern

Time:07-18

Ok... So I am trying to wrap my head around properties. I have done a ton of googling but really need to try myself to fully understand. I have 3 components:

  1. I have a UserForm: "frmView1"
  2. I have a class module: "clsPresenter1"
  3. I have a regular module: "modModel1"

My UserForm has a txtbox "TextBox1" and here is the userform code:

Option Explicit

'View (The V in MVP)

Public Event OnTxtBoxChange()

Public Property Get TxtBoxInfo() As String

    TxtBoxInfo = TextBox1.Text

End Property

Private Sub TextBox1_Change()

    RaiseEvent OnTxtBoxChange

End Sub

My Class module:

Option Explicit

'Presenter Class (The P in MVP)
'Implements Business Logic

Private WithEvents objUserForm As frmView1

Private Sub Class_Initialize()

    Set objUserForm = New frmView1

End Sub

Public Sub TxtBoxContent()

    objUserForm.TxtBoxInfo

End Sub

Private Sub objUserForm_OnTxtBoxChange()

    DoSomething

End Sub

My regular module:

Option Explicit

'Model Module (The M in MVP)
'Business Logic
Private objPresenter As clsPresenter1

Public Sub DoSomething()

    Sheet1.Cells.Clear
    Sheet1.Cells(3, 3) = objPresenter.TxtBoxContent   

End Sub

So this is a shortened version to simplify my question. In reality I have code to show the form and close the form and a few other things that are working fine. But my question is... How do I pass whatever the user types in the txt box to the worksheet? I keep getting:

Compile error: Expected Function or variable

CodePudding user response:

Ok... So I may have figured it out... I changed:

Public Sub TxtBoxContent()

    objUserForm.TxtBoxInfo

End Sub

To:

Public Function TxtBoxContent() As String

    TxtBoxContent = objUserForm.TxtBoxInfo

End Function

This seems to work... Please let me know if this is not the correct way...

CodePudding user response:

Ugh... So this works also... Maybe this is actually the correct way? Again changing:

Public Sub TxtBoxContent()

    objUserForm.TxtBoxInfo

End Sub

To:

Public Property Get TxtBoxContent() As String

    TxtBoxContent = objUserForm.TxtBoxInfo

End Property

Again this seems to work... But why would I ever us a function in my class module ("presenter") if I could always use a property instead?

  • Related