Is there a VBA code that can set the column widths of selected columns for all sheets in…
- User
Is there a VBA code that can set the column widths of selected columns for all sheets in a workbook
- Assistant
Yes, you can use the following VBA code to set the column widths of selected columns for all sheets in a workbook:
Sub SetColumnWidths() Dim ws As Worksheet Dim selectedColumns As Range Dim columnWidth As Double ' Set the column width (change it as per your requirement) columnWidth = 15 ' Select the columns you want to apply the width to Set selectedColumns = Application.InputBox("Select the columns to set width", Type:=8) ' Loop through each worksheet in the workbook For Each ws In ThisWorkbook.Sheets ws.Activate selectedColumns.EntireColumn.ColumnWidth = columnWidth Next ws End SubTo use this code, press
Alt + F11to open the VBA editor. Insert a new module and paste the above code into it. Then, run theSetColumnWidthsmacro. It will prompt you to select the columns you want to set the width for, and then it will apply the specified width to those columns in all the sheets of the workbook. - User
Is it possible to set column widths in this way, column1 set to , column 2 to 5 set to, column 6 set to, column 7 to 10 set to etc
- Assistant
Yes, it is possible to set column widths for specific columns using a VBA code. Here is an example of how you can do it:
Sub SetColumnWidths() Dim ws As Worksheet Dim columnWidths() As Variant Dim i As Long ' Define the column widths for each column columnWidths = Array( _ Array(1, 10), _ Array(2, 5), _ Array(6, 3), _ Array(7, 10) _ ) ' Loop through each worksheet in the workbook For Each ws In ThisWorkbook.Sheets ws.Activate ' Loop through each column width definition For i = LBound(columnWidths) To UBound(columnWidths) Dim colIndex As Long Dim widthValue As Double colIndex = columnWidths(i)(0) ' column index widthValue = columnWidths(i)(1) ' width value Columns(colIndex).ColumnWidth = widthValue Next i Next ws End SubIn this example, the
columnWidthsarray is used to define the column index and the corresponding width for each column you want to set. You can add or modify theArray()lines to define the column index and width values according to your requirements.Running the
SetColumnWidthsmacro will apply the specified column widths to the corresponding columns in all worksheets of the workbook.