vba - How to loop through each column in Excel and apply column width based on condition -
i in need of excel vba code autofit columns default , loop through each column width , if width exceeds particular value eg., 50, restrict particular column width 30 , sets word wrap true.
public function lastcolumn(optional wks worksheet) long if wks nothing then: set wks = activesheet lastcolumn = cells.find("*", searchorder:=xlbycolumns, searchdirection:=xlprevious).column end function sub macro1() dim lastcol long cells.select cells.entirecolumn.autofit lastcol = lastcolumn(thisworkbook.sheets("sheet1")) = 1 lastcol if columns(i).columnwidth > 70 columns(i).columnwidth = 70 columns(i).wraptext = true end if next end sub
is there better way achieve this?
something like
sub autofit() dim col range each col in activesheet.usedrange.columns 'only columns have values col.autofit if col.columnwidth > 50 'set values here col.columnwidth = 30 col.wraptext = true end if next end sub
note, uses excel widths, not pixels
Comments
Post a Comment