icrlp05
icrlp05

Reputation: 1

Completing VBA Userform textboxes from Excel Cell

I'm trying to fill in a userform ("Userform1") textboxes ("SecurityTextBox", "VersionTextbox") from an Excel Sheet ("Version"). I've tried to look up what's going wrong but I haven't managed to figure it out.

Private Sub UserForm1_Initialize()
Dim ws As Worksheet
Set ws = Worksheets("Version")

SecurityTextBox.Text = ws.Cells.Range("C8").Value
VersionTextbox.Text = ws.Cells.Range("C13").Value
DeveloperTextBox.Text = ws.Cells.Range("C14").Value

End Sub

The trouble is the text boxes are just appearing blank.

Upvotes: 0

Views: 435

Answers (1)

Mathieu Guindon
Mathieu Guindon

Reputation: 71227

The _Initialize handler is invoked when the class/form instance is created. If you're showing the form like this:

UserForm1.Show

Then it might work as expected if that's the only thing you're ever doing with the form. Problem is, it's the form's default instance, and you don't quite control when VBA is going to initialize that global instance.

Take control.

With New UserForm1 'initializes a new instance of the class
    .Show
End With

Now the _Initialize handler with systematically run every time, because it's a New instance every time. See my UserForm1.Show article for more pitfalls of using forms' default instances.

Upvotes: 1

Related Questions