code doesn't work in initialize userform

Hasson

Board Regular
Joined
Apr 8, 2021
Messages
120
Office Version
  1. 2016
Platform
  1. Windows
hi
I have this code doesn't work in initialize user form . it just work in commandbutton when I put this
VBA Code:
Private Sub CommandButton1_Click()

Dim n As Long, Rws As String
With ListBox1
For n = 0 To .ListCount - 1
    If .Selected(n) Then
        Rws = Rws & IIf(Rws = "", n + 1, ", " & n + 1)
    End If
Next n
If Rws <> "" Then
TextBox1.Value = Rws
MsgBox "Selected Rows :- " & Rws
End If
End With

End Sub

but when I put into initialize user form
Code:
Private Sub UserForm_Initialize()
  
    Dim n As Long, Rws As String
With ListBox1
.ListBox1.List = Sheets("Sheet1").ListObjects("Table1").DataBodyRange.Value
For n = 0 To .ListCount - 1
    If .Selected(n) Then
        Rws = Rws & IIf(Rws = "", n + 1, ", " & n + 1)
    End If
Next n
If Rws <> "" Then
TextBox1.Value = Rws
MsgBox "Selected Rows :- " & Rws
End If
End With

End Sub
it doesn't work at all
my request when I select item from listbox automatically show the number of row in textbox1
any suggestion to fix it ,please ?
 

Excel Facts

Workdays for a market open Mon, Wed, Friday?
Yes! Use "0101011" for the weekend argument in NETWORKDAYS.INTL or WORKDAY.INTL. The 7 digits start on Monday. 1 means it is a weekend.

Fluff

MrExcel MVP, Moderator
Joined
Jun 12, 2014
Messages
64,085
Office Version
  1. 365
Platform
  1. Windows
You need to put the code into the listbox click event.
 
Solution

Hasson

Board Regular
Joined
Apr 8, 2021
Messages
120
Office Version
  1. 2016
Platform
  1. Windows
thanks professional
it helped me so much(y)
 

Fluff

MrExcel MVP, Moderator
Joined
Jun 12, 2014
Messages
64,085
Office Version
  1. 365
Platform
  1. Windows
You're welcome & thanks for the feedback.
 

Forum statistics

Threads
1,144,568
Messages
5,725,046
Members
422,590
Latest member
Mikeyyy

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Top