title: How to loop through each column in Excel and apply column width based on condition
body: <p>I am in need of excel vba code that will autofit all columns by default and then loop through each column width and if any width exceeds a particular value eg., 50, then restrict that particular column width to 30 and sets word wrap to true.</p>
  
  <pre><code>Public Function LastColumn(Optional wks As Worksheet) As Long
      If wks Is Nothing Then: Set wks = ActiveSheet
      LastColumn = Cells.Find("*", SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column
  End Function
  
  
  Sub Macro1()
      Dim LastCol As Long
      Cells.Select
      Cells.EntireColumn.AutoFit
      LastCol = LastColumn(ThisWorkbook.Sheets("Sheet1"))
      For i = 1 To LastCol
          If Columns(i).ColumnWidth &gt; 70 Then
              Columns(i).ColumnWidth = 70
              Columns(i).WrapText = True
          End If
      Next i
  End Sub
  </code></pre>
  
  <p>Is there a better way to achieve this?</p>