VBA help with column Width

decadence

Well-known Member
Joined
Oct 9, 2015
Messages
525
Office Version
  1. 365
  2. 2016
  3. 2013
  4. 2010
  5. 2007
Platform
  1. Windows
Hi, I am trying to determine the column width but not sure how. What I wold like to do is:

If it is smaller than a specific number then auto fit that column

If the width is bigger than that number then set the column width to that number

Can someone help please.

Here is What I have so far

Code:
Sub ColWidth()

    Dim x2 As range, Rng As range
    Set Rng = range("A1:H1")
    For Each x2 In Rng
        If InStr(1, x2.Value, "Apple") > 0 Then
                If x2.Width <> 5 Then
                    x2.EntireColumn.ColumnWidth = 5
                End If
        ElseIf InStr(1, x2.Value, "Banana") > 0 Then
            If x2.Width <> 12.5 Then
                x2.EntireColumn.ColumnWidth = 12.5
            End If
        ElseIf InStr(1, x2.Value, "Orange") > 0 Then
                If x2.Width <> 20 Then
                    x2.EntireColumn.ColumnWidth = 20
                End If
        End If
    Next x2
End Sub
 

Excel Facts

Test for Multiple Conditions in IF?
Use AND(test, test, test, test) or OR(test, test, test, ...) as the logical_test argument of IF.
something like

Code:
w = 10
If Columns(w).Width < 200 Then Columns(w).EntireColumn.AutoFit

hth,
Ross
 
Last edited:
Upvote 0

Forum statistics

Threads
1,223,894
Messages
6,175,252
Members
452,623
Latest member
Techenthusiast

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