how could autofit columns in listbox without specify values for each column

tubrak

Board Regular
Joined
May 30, 2021
Messages
216
Office Version
  1. 2019
Platform
  1. Windows
Hi Guys

I need procedure to fit columns in listbox without specify values . should expand and contracts and control margins for width based on size of data for each column.

so when run the userform or search for data should autofill columns in listbox
I look forward to add some procedures to do that
VBA Code:
Private Sub UserForm_Initialize()
  Dim LastRow As Long
  Set sh = ActiveSheet
  a = sh.Range("A1:F" & sh.Range("A" & Rows.Count).End(xlUp)).Value
  With MY_List
    .ColumnCount = 7
    .ColumnWidths = "20;50;100;100;70;70;70"
    Call CommandButton4_Click
  End With
End Sub
thanks
 
Indeed it is because of the font size that you have in listbox. try like this:

VBA Code:
Private Sub UserForm_Initialize()
  Dim i As Long, nmax As Long
  Dim sWidths As String
  
  Set sh = ActiveSheet
  sh.Columns("A:F").EntireColumn.AutoFit
  a = sh.Range("A1:F" & sh.Range("A" & Rows.Count).End(xlUp).Row).Value
  
  For i = 1 To 4
    sWidths = sWidths & Int(sh.Cells(1, i).Width) + 40 & "  pt; "
  Next
  nmax = WorksheetFunction.Max(Int(sh.Cells(1, "E").Width), Int(sh.Cells(1, "F").Width))
  sWidths = sWidths & nmax + 40 & "  pt; " & nmax + 40 & " pt; " & nmax + 40 & " pt"
  With MY_List
    .ColumnCount = 7
    .ColumnWidths = sWidths
    Call CommandButton4_Click
  End With
End Sub

Result:
1674780619146.png
 
Upvote 0
Solution

Excel Facts

Convert text numbers to real numbers
Select a column containing text numbers. Press Alt+D E F to quickly convert text to numbers. Faster than "Convert to Number"

Forum statistics

Threads
1,215,429
Messages
6,124,842
Members
449,193
Latest member
MikeVol

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
Back
Top