In this VBA Tutorial, you learn how to use Excel VBA to set or autofit the width of columns in a variety of circumstances.
This VBA Tutorial is accompanied by Excel workbooks containing the data and macros I use in the examples below. You can get immediate free access to these example workbooks by subscribing to the Power Spreadsheets Newsletter.
Use the following Table of Contents to navigate to the section you’re interested in.
Related VBA and Macro Tutorials
The following VBA and Macro Tutorials may help you better understand and implement the contents below:
- General VBA constructs and structures:
- Learn about using variables here.
- Learn about VBA data types here.
- Learn about R1C1 and A1 style references here.
- Practical VBA applications and macro examples:
- Learn how to work with worksheets here.
- Learn how to delete columns here.
- Learn how to hide or unhide rows and columns here.
You can find additional VBA and Macro Tutorials in the Archives.
#1: Set Column Width
VBA Code to Set Column Width
To set the width of a column with VBA, use a statement with the following structure:
Worksheet.Range("A1CellReference").ColumnWidth = ColumnWidthUnits
Process Followed by VBA Code
Specify column width in units” width=”316″ height=”102″>
VBA Statement Explanation
- Item: Worksheet.
- VBA Construct: Workbook.Worksheets property.
- Description: Returns a Worksheet object representing the worksheet you work with.
- Item: Range(“A1CellReference”).
- VBA Construct: Worksheet.Range property.
- Description: Returns a Range object representing a cell within the column whose width you set. You specify the cell using an A1-style cell reference (A1CellReference) enclosed within quotations (“”).
- Item: ColumnWidth.
- VBA Construct: Range.ColumnWidth property.
- Description: Sets the width of the column containing the Range object returned by item #2 above.
- Item: ColumnWidthUnits.
- VBA Construct: New value of the Range.ColumnWidth property.
- Description: Specifies the width, in units, of the column containing the Range object returned by item #2 above.
- Column width isn’t measured in points, centimeters or inches. Excel measures column width units based on the size (width) of the font you use in the Normal style (for example, Calibri 11).
- Therefore, 1 unit of column width is equal to 1 character of the Normal style font. Consider the following:
- If your Normal style font is a fixed-width font, such as Courier New or Consolas, all characters have the same width.
- If your Normal style font is a proportional font, Excel considers the width of the character “0” (the number zero).
- If you explicitly declare a variable to represent ColumnWidthUnits, use a numeric data type that can handle the value you use to specify the column width in the appropriate units.
Macro Example
The following macro sets the width of column A of the worksheet named “Column width” to 15 units.
Sub columnWidth() 'Source: https://powerspreadsheets.com/ 'For further information: https://powerspreadsheets.com/excel-vba-column-width/ Worksheets("Column width").Range("A5").columnWidth = 15 End Sub
Effects of Executing Macro Example
The following GIF illustrates the results of executing this macro example. As expected, VBA sets the width of column A to 15 units.
#2: Set Column Width for Multiple Contiguous Columns
VBA Code to Set Column Width for Multiple Contiguous Columns
To set the width of multiple contiguous columns with VBA, use a statement with the following structure:
Worksheet.Range("FirstColumnLetter:LastColumnLetter").ColumnWidth = ColumnWidthUnits
Process Followed by VBA Code
Specify column width in units” width=”312″ height=”105″>
VBA Statement Explanation
- Item: Worksheet.
- VBA Construct: Workbook.Worksheets property.
- Description: Returns a Worksheet object representing the worksheet you work with.
- Item: Range(“FirstColumnLetter:LastColumnLetter”).
- VBA Construct: Worksheet.Range property.
- Description: Returns a Range object representing the columns whose width you set. Under this syntax:
- You identify columns by the letters of their headers (FirstColumnLetter and LastColumnLetter).
- The column letters are:
- Separated by a colon (:), which allows you to set up an array.
- Enclosed within quotations (“”).
- Item: ColumnWidth.
- VBA Construct: Range.ColumnWidth property.
- Description: Sets the width of the columns returned by item #2 above.
- Item: ColumnWidthUnits.
- VBA Construct: New value of the Range.ColumnWidth property.
- Description: Specifies the width, in units, of the columns returned by item #2 above.
- Column width isn’t measured in points, centimeters or inches. Excel measures column width units based on the size (width) of the font you use in the Normal style (for example, Calibri 11).
- Therefore, 1 unit of column width is equal to 1 character of the Normal style font. Consider the following:
- If your Normal style font is a fixed-width font, such as Courier New or Consolas, all characters have the same width.
- If your Normal style font is a proportional font, Excel considers the width of the character “0” (the number zero).
- If you explicitly declare a variable to represent ColumnWidthUnits, use a numeric data type that can handle the value you use to specify the column width in the appropriate units.
Macro Example
The following macro sets the width of columns C through E (C, D and E) of the worksheet named “Column width” to 10 units.
Sub columnWidthMultipleColumns() 'Source: https://powerspreadsheets.com/ 'For further information: https://powerspreadsheets.com/excel-vba-column-width/ Worksheets("Column width").Range("C:E").columnWidth = 10 End Sub
Effects of Executing Macro Example
The following GIF illustrates the results of executing this macro example. As expected, VBA sets the width of columns C through E to 10 units.
#3: Set Column Width for Multiple Non-Contiguous Columns
VBA Code to Set Column Width for Multiple Non-Contiguous Columns
To set the width of multiple non-contiguous columns with VBA, use a statement with the following structure:
Worksheet.Range("Column1Area1Letter:ColumnLastArea1Letter,Column1Area2Letter:ColumnLastArea2Letter, ... , Column1AreaLastLetter:ColumnLastAreaLastLetter").ColumnWidth = ColumnWidthUnits
Process Followed by VBA Code
Specify column width in units” width=”312″ height=”105″>
VBA Statement Explanation
- Item: Worksheet.
- VBA Construct: Workbook.Worksheets property.
- Description: Returns a Worksheet object representing the worksheet you work with.
- Item: Range(“Column1Area1Letter:ColumnLastArea1Letter,Column1Area2Letter:ColumnLastArea2Letter, … , Column1AreaLastLetter:ColumnLastAreaLastLetter”).
- VBA Construct: Worksheet.Range property.
- Description: Returns a Range object representing the columns whose width you set. Under this syntax:
- You identify columns by the letters of their headers (Column1Area1Letter, ColumnLastArea1Letter, Column1Area2Letter, ColumnLastArea2Letter, … , Column1AreaLastLetter and ColumnLastAreaLastLetter”).
- The column letters identifying contiguous columns (within the same data area) are separated by a colon (:), which allows you to set up an array. If you’re only referring to a single column (for example, column B), include the letter reference twice and separate them with a colon (:) (for example “B:B”).
- The column letters identifying non-contiguous columns (in separate data areas) are separated by the union operator, a comma (,).
- The complete column reference is enclosed within quotations (“”).
- Item: ColumnWidth.
- VBA Construct: Range.ColumnWidth property.
- Description: Sets the width of the columns returned by item #2 above.
- Item: ColumnWidthUnits.
- VBA Construct: New value of the Range.ColumnWidth property.
- Description: Specifies the width, in units, of the columns returned by item #2 above.
- Column width isn’t measured in points, centimeters or inches. Excel measures column width units based on the size (width) of the font you use in the Normal style (for example, Calibri 11).
- Therefore, 1 unit of column width is equal to 1 character of the Normal style font. Consider the following:
- If your Normal style font is a fixed-width font, such as Courier New or Consolas, all characters have the same width.
- If your Normal style font is a proportional font, Excel considers the width of the character “0” (the number zero).
- If you explicitly declare a variable to represent ColumnWidthUnits, use a numeric data type that can handle the value you use to specify the column width in the appropriate units.
Macro Example
The following macro sets the width of columns B, F and H of the worksheet named “Column width” to 20 units.
Sub columnWidthMultipleNonAdjacentColumns() 'Source: https://powerspreadsheets.com/ 'For further information: https://powerspreadsheets.com/excel-vba-column-width/ Worksheets("Column width").Range("B:B,F:F,H:H").columnWidth = 20 End Sub
Effects of Executing Macro Example
The following GIF illustrates the results of executing this macro example. As expected, VBA sets the width of columns B, F and H to 20 units.
#4: AutoFit Column Width Based on Entire Column
VBA Code to AutoFit Column Width Based on Entire Column
To autofit the width of a column with VBA, considering the contents of the entire column, use a statement with the following structure:
Worksheet.Range("A1CellReference").EntireColumn.AutoFit
Process Followed by VBA Code
return entire column > autofit entire column width” width=”497″ height=”107″>
VBA Statement Explanation
- Item: Worksheet.
- VBA Construct: Workbook.Worksheets property.
- Description: Returns a Worksheet object representing the worksheet you work with.
- Item: Range(“A1CellReference”).
- VBA Construct: Worksheet.Range property.
- Description: Returns a Range object representing a cell within the column you autofit. You specify the cell using an A1-style cell reference (A1CellReference) enclosed within quotations (“”).
- Item: EntireColumn.
- VBA Construct: Range.EntireColumn property.
- Description: Returns a Range object representing the entire column containing the Range object returned by item #2 above.
- Item: AutoFit.
- VBA Construct: Range.AutoFit method.
- Description: Modifies the width of the column represented by the Range object returned by item #3 above to achieve the best fit (autofits).
Macro Example
The following macro autofits the width of column G of the worksheet named “Column width” based on the contents of all the cells in the entire column.
Sub columnWidthAutoFitEntireColumn() 'Source: https://powerspreadsheets.com/ 'For further information: https://powerspreadsheets.com/excel-vba-column-width/ Worksheets("Column width").Range("G5").EntireColumn.AutoFit End Sub
Effects of Executing Macro Example
The following GIF illustrates the results of executing this macro example. As expected, VBA autofits the width of column G based on the contents of all the cells in the entire column. Notice the contents in cell G10 (Autofit based on entire column), which are used as the basis for the autofitting operation.
#5: AutoFit Column Width Based on Specific Cell
VBA Code to AutoFit Column Width Based on Specific Cell
To autofit the width of a column with VBA, considering the contents of a specific cell or row, use a statement with the following structure:
Worksheet.Range("A1CellReference").Columns.AutoFit
Process Followed by VBA Code
return column > autofit entire column width to contents of cell” width=”493″ height=”105″>
VBA Statement Explanation
- Item: Worksheet.
- VBA Construct: Workbook.Worksheets property.
- Description: Returns a Worksheet object representing the worksheet you work with.
- Item: Range(“A1CellReference”).
- VBA Construct: Worksheet.Range property.
- Description: Returns a Range object representing a cell.
- This cell:
- Is within the column you autofit.
- Is the cell whose contents Excel considers for purposes of achieving the best fit (autofitting).
- You specify the cell using an A1-style cell reference (A1CellReference) enclosed within quotations (“”).
- This cell:
- Item: Columns.
- VBA Construct: Range.Columns property.
- Description: Returns a Range object representing the column containing the Range object returned by item #2 above.
- Item: AutoFit.
- VBA Construct: Range.AutoFit method.
- Description: Modifies the width of the column represented by the Range object returned by item #3 above to achieve the best fit (autofits) based on the contents within the cell represented by the Range object returned by item #2 above.
Macro Example
The following macro autofits the width of column I of the worksheet named “Column width” based on the contents of cell I5.
Sub columnWidthAutoFitRow() 'Source: https://powerspreadsheets.com/ 'For further information: https://powerspreadsheets.com/excel-vba-column-width/ Worksheets("Column width").Range("I5").Columns.AutoFit End Sub
Effects of Executing Macro Example
The following GIF illustrates the results of executing this macro example. As expected, VBA sets autofits the width of column I based on the contents of cell I5. Notice the contents in cell I10 (Autofit based on specific cell), which aren’t used as the basis for the autofitting operation.
#6: Set Column Width in Points
VBA Code to Set Column Width in Points
To set the width of a column in points with VBA, use a macro with the following statement structure:
With Worksheet.Range("A1CellReference") For Counter = 1 To 3 .ColumnWidth = ColumnWidthPoints * (.ColumnWidth / .Width) Next Counter End With
Process Followed by VBA Code
specify column width in points 3 times” width=”689″ height=”192″>
VBA Statement Explanation
Lines #1 and #5: With Worksheet.Range(“A1CellReference”) | End With
- Item: With… End With.
- VBA Construct: With… End With statement.
- Description: Statements within the With… End With statement (lines # through #4 below) are executed on the Range object returned by item #3 below.
- Item: Worksheet.
- VBA Construct: Workbook.Worksheets property.
- Description: Returns a Worksheet object representing the worksheet you work with.
- Item: Range(“A1CellReference”).
- VBA Construct: Worksheet.Range property.
- Description: Returns a Range object representing a cell within the column whose width you set. You specify the cell using an A1-style cell reference (A1CellReference) enclosed within quotations (“”).
Lines #2 and #4: For Counter = 1 To 3 | Next Counter
- Item: For… Next Counter.
- VBA Construct: For… Next statement.
- Description: Repeats the statement within the loop (line #3 below) 3 times, as required by item #3 below.
- Item: Counter.
- VBA Construct: Counter of For… Next statement.
- Description: Loop counter. If you explicitly declare a variable to represent the loop counter, use the Long data type.
- Item: 1 To 3.
- VBA Construct: Counter Start (1) and Counter End (3) of For… Next statement.
- Description: The statement within the loop (line #3 below) is executed 3 times (1 To 3).
- Theoretically, line #3 below should be enough to set the column width in points without requiring the loop specified by these lines #2 and #4. In practice, this may not be the case. Some tests suggest that repeating line #3 below (or similar) 3 times generally gets you the closest to the specified column width.
Line #3: .ColumnWidth = ColumnWidthPoints * (.ColumnWidth / .Width)
- Item: .ColumnWidth.
- VBA Construct: Range.ColumnWidth property.
- Description:
- Sets the width of the column containing the Range object within the opening statement of the With… End With block (line #1, item #3 above).
- .ColumnWidth is included twice in the statement. In this first mention, (.ColumnWidth = …), ColumnWidth is the property to which a value is assigned. The value assigned to the ColumnWidth property is the value returned by the other items within this statement.
- Item: ColumnWidthPoints.
- VBA Construct: Numeric (for example, Double) variable.
- Description: Specifies the width (in points) of the columns containing the Range object within the opening statement of the With… End With block (line #1, item #3 above).
- If you explicitly declare a variable to represent ColumnWidthPoints, use a numeric data type that can handle the value you use to specify the column width in points.
- Item: .ColumnWidth.
- VBA Construct: Range.ColumnWidth property.
- Description:
- Returns the width of the column containing the Range object within the opening statement of the With… End With block (line #1, item #3 above).
- .ColumnWidth is included twice in the statement. In this second mention, (.ColumnWidth), ColumnWidth returns the current value of the property.
- The ColumnWidth property returns the column width in units based on the size (width) of the font you use in the Normal style (for example, Calibri 11). Therefore, 1 unit of column width is equal to 1 character of the Normal style font. If your Normal style font is a proportional (not fixed-width) font, Excel considers the width of the character “0” (the number zero).
- Item: .Width.
- VBA Construct: Range.Width property.
- Description:
- Returns the width of the column containing the Range object within the opening statement of the With… End With block (line #1, item #3 above).
- The Width property returns the column width in points.
- Item: (.ColumnWidth / .Width).
- VBA Construct: Numeric expression.
- Description:
- Both ColumnWidth (item #3 above) and Width (item #4 above) return the width of the column containing the Range object within the opening statement of the With… End With block (line #1, item #3 above).
- The units in which ColumnWidth and Width return the column width differ.
- ColumnWidth expresses the column width in units based on the size (width) of the font you use in the Normal style.
- Width expresses the column width in points.
- ColumnWidth divided by Width (.ColumnWidth / .Width) returns the factor by which you must multiply the desired column width expressed in points (item #2 above) to obtain the appropriate column width in units based on the size (width) of the font you use in the Normal style. In other words, this expression converts ColumnWidthPoints from points to the units required by the ColumnWidth property.
Macro Example
The following macro sets the width of column J of the worksheet named “Column width” to 80 points.
Sub columnWidthPoints() 'Source: https://powerspreadsheets.com/ 'For further information: https://powerspreadsheets.com/excel-vba-column-width/ Dim iCounter As Long With Worksheets("Column width").Range("J5") For iCounter = 1 To 3 .columnWidth = 80 * (.columnWidth / .Width) Next iCounter End With End Sub
Effects of Executing Macro Example
The following GIF illustrates the results of executing this macro example. As expected, VBA sets the width of column J to 80 points.
#7: Set Column Width in Inches
VBA Code to Set Column Width in Inches
To set the width of a column in inches with VBA, use a macro with the following statement structure:
With Worksheet.Range("A1CellReference") For Counter = 1 To 3 .ColumnWidth = Application.InchesToPoints(ColumnWidthInches) * (.ColumnWidth / .Width) Next Counter End With
Process Followed by VBA Code
specify column width in inches 3 times” width=”686″ height=”191″>
VBA Statement Explanation
Lines #1 and #5: With Worksheet.Range(“A1CellReference”) | End With
- Item: With… End With.
- VBA Construct: With… End With statement.
- Description: Statements within the With… End With statement (lines # through #4 below) are executed on the Range object returned by item #3 below.
- Item: Worksheet.
- VBA Construct: Workbook.Worksheets property.
- Description: Returns a Worksheet object representing the worksheet you work with.
- Item: Range(“A1CellReference”).
- VBA Construct: Worksheet.Range property.
- Description: Returns a Range object representing a cell within the column whose width you set. You specify the cell using an A1-style cell reference (A1CellReference) enclosed within quotations (“”).
Lines #2 and #4: For Counter = 1 To 3 | Next Counter
- Item: For… Next Counter.
- VBA Construct: For… Next statement.
- Description: Repeats the statement within the loop (line #3 below) 3 times, as required by item #3 below.
- Item: Counter.
- VBA Construct: Counter of For… Next statement.
- Description: Loop counter. If you explicitly declare a variable to represent the loop counter, use the Long data type.
- Item: 1 To 3.
- VBA Construct: Counter Start (1) and Counter End (3) of For… Next statement.
- Description: The statement within the loop (line #3 below) is executed 3 times (1 To 3).
- Theoretically, line #3 below should be enough to set the column width in inches without requiring the loop specified by these lines #2 and #4. In practice, this may not be the case. Some tests suggest that repeating line #3 below (or similar) 3 times generally gets you the closest to the specified column width.
Line #3: .ColumnWidth = Application.InchesToPoints(ColumnWidthInches) * (.ColumnWidth / .Width)
- Item: .ColumnWidth.
- VBA Construct: Range.ColumnWidth property.
- Description:
- Sets the width of the column containing the Range object within the opening statement of the With… End With block (line #1, item #3 above).
- .ColumnWidth is included twice in the statement. In this first mention, (.ColumnWidth = …), ColumnWidth is the property to which a value is assigned. The value assigned to the ColumnWidth property is the value returned by the other items within this statement.
- Item: Application.InchesToPoints.
- VBA Construct: Application.InchesToPoints method.
- Description: Converts the measurement specified by item #3 below from inches to points.
- Item: ColumnWidthInches.
- VBA Construct: Inches parameter of Application.InchesToPoints method.
- Description: Specifies the width (in inches) of the columns containing the Range object within the opening statement of the With… End With block (line #1, item #3 above).
- If you explicitly declare a variable to represent ColumnWidthInches, use a numeric data type that can handle the value you use to specify the column width in inches.
- Item: .ColumnWidth.
- VBA Construct: Range.ColumnWidth property.
- Description:
- Returns the width of the column containing the Range object within the opening statement of the With… End With block (line #1, item #3 above).
- .ColumnWidth is included twice in the statement. In this second mention, (.ColumnWidth), ColumnWidth returns the current value of the property.
- The ColumnWidth property returns the column width in units based on the size (width) of the font you use in the Normal style (for example, Calibri 11). Therefore, 1 unit of column width is equal to 1 character of the Normal style font. If your Normal style font is a proportional (not fixed-width) font, Excel considers the width of the character “0” (the number zero).
- Item: .Width.
- VBA Construct: Range.Width property.
- Description:
- Returns the width of the column containing the Range object within the opening statement of the With… End With block (line #1, item #3 above).
- The Width property returns the column width in points.
- Item: (.ColumnWidth / .Width).
- VBA Construct: Numeric expression.
- Description:
- Both ColumnWidth (item #4 above) and Width (item #5 above) return the width of the column containing the Range object within the opening statement of the With… End With block (line #1, item #3 above).
- The units in which ColumnWidth and Width return the column width differ.
- ColumnWidth expresses the column width in units based on the size (width) of the font you use in the Normal style.
- Width expresses the column width in points.
- ColumnWidth divided by Width (.ColumnWidth / .Width) returns the factor by which you must multiply the desired column width expressed in inches/points (items #2 and #3 above) to obtain the appropriate column width in units based on the size (width) of the font you use in the Normal style. In other words, this expression converts Application.InchesToPoints(ColumnWidthInches) from points to the units required by the ColumnWidth property.
Macro Example
The following macro sets the width of column K of the worksheet named “Column width” to 1 inch.
Sub columnWidthInches() 'Source: https://powerspreadsheets.com/ 'For further information: https://powerspreadsheets.com/excel-vba-column-width/ Dim iCounter As Long With Worksheets("Column width").Range("K5") For iCounter = 1 To 3 .columnWidth = Application.InchesToPoints(1) * (.columnWidth / .Width) Next iCounter End With End Sub
Effects of Executing Macro Example
The following GIF illustrates the results of executing this macro example. As expected, VBA sets the width of column K to 1 inch.
#8: Set Column Width in Centimeters
VBA Code to Set Column Width in Centimeters
To set the width of a column in centimeters with VBA, use a macro with the following statement structure:
With Worksheet.Range("A1CellReference") For Counter = 1 To 3 .ColumnWidth = Application.CentimetersToPoints(ColumnWidthCentimeters) * (.ColumnWidth / .Width) Next Counter End With
Process Followed by VBA Code
specify column width in centimeters 3 times” width=”683″ height=”192″>
VBA Statement Explanation
Lines #1 and #5: With Worksheet.Range(“A1CellReference”) | End With
- Item: With… End With.
- VBA Construct: With… End With statement.
- Description: Statements within the With… End With statement (lines # through #4 below) are executed on the Range object returned by item #3 below.
- Item: Worksheet.
- VBA Construct: Workbook.Worksheets property.
- Description: Returns a Worksheet object representing the worksheet you work with.
- Item: Range(“A1CellReference”).
- VBA Construct: Worksheet.Range property.
- Description: Returns a Range object representing a cell within the column whose width you set. You specify the cell using an A1-style cell reference (A1CellReference) enclosed within quotations (“”).
Lines #2 and #4: For Counter = 1 To 3 | Next Counter
- Item: For… Next Counter.
- VBA Construct: For… Next statement.
- Description: Repeats the statement within the loop (line #3 below) 3 times, as required by item #3 below.
- Item: Counter.
- VBA Construct: Counter of For… Next statement.
- Description: Loop counter. If you explicitly declare a variable to represent the loop counter, use the Long data type.
- Item: 1 To 3.
- VBA Construct: Counter Start (1) and Counter End (3) of For… Next statement.
- Description: The statement within the loop (line #3 below) is executed 3 times (1 To 3).
- Theoretically, line #3 below should be enough to set the column width in centimeters without requiring the loop specified by these lines #2 and #4. In practice, this may not be the case. Some tests suggest that repeating line #3 below (or similar) 3 times generally gets you the closest to the specified column width.
Line #3: .ColumnWidth = Application.CentimetersToPoints(ColumnWidthCentimeters) * (.ColumnWidth / .Width)
- Item: .ColumnWidth.
- VBA Construct: Range.ColumnWidth property.
- Description:
- Sets the width of the column containing the Range object within the opening statement of the With… End With block (line #1, item #3 above).
- .ColumnWidth is included twice in the statement. In this first mention, (.ColumnWidth = …), ColumnWidth is the property to which a value is assigned. The value assigned to the ColumnWidth property is the value returned by the other items within this statement.
- Item: Application.CentimetersToPoints.
- VBA Construct: Application.CentimetersToPoints method.
- Description: Converts the measurement specified by item #3 below from centimeters to points.
- Item: ColumnWidthCentimeters.
- VBA Construct: Centimeters parameter of Application.CentimetersToPoints method.
- Description: Specifies the width (in centimeters) of the columns containing the Range object within the opening statement of the With… End With block (line #1, item #3 above).
- If you explicitly declare a variable to represent ColumnWidthCentimeters, use a numeric data type that can handle the value you use to specify the column width in centimeters.
- Item: .ColumnWidth.
- VBA Construct: Range.ColumnWidth property.
- Description:
- Returns the width of the column containing the Range object within the opening statement of the With… End With block (line #1, item #3 above).
- .ColumnWidth is included twice in the statement. In this second mention, (.ColumnWidth), ColumnWidth returns the current value of the property.
- The ColumnWidth property returns the column width in units based on the size (width) of the font you use in the Normal style (for example, Calibri 11). Therefore, 1 unit of column width is equal to 1 character of the Normal style font. If your Normal style font is a proportional (not fixed-width) font, Excel considers the width of the character “0” (the number zero).
- Item: .Width.
- VBA Construct: Range.Width property.
- Description:
- Returns the width of the column containing the Range object within the opening statement of the With… End With block (line #1, item #3 above).
- The Width property returns the column width in points.
- Item: (.ColumnWidth / .Width).
- VBA Construct: Numeric expression.
- Description:
- Both ColumnWidth (item #4 above) and Width (item #5 above) return the width of the column containing the Range object within the opening statement of the With… End With block (line #1, item #3 above).
- The units in which ColumnWidth and Width return the column width differ.
- ColumnWidth expresses the column width in units based on the size (width) of the font you use in the Normal style.
- Width expresses the column width in points.
- ColumnWidth divided by Width (.ColumnWidth / .Width) returns the factor by which you must multiply the desired column width expressed in centimeters/points (items #2 and #3 above) to obtain the appropriate column width in units based on the size (width) of the font you use in the Normal style. In other words, this expression converts Application.CentimetersToPoints(ColumnWidthCentimeters) from points to the units required by the ColumnWidth property.
Macro Example
The following macro sets the width of column L of the worksheet named “Column width” to 1 centimeter.
Sub columnWidthCentimeters() 'Source: https://powerspreadsheets.com/ 'For further information: https://powerspreadsheets.com/excel-vba-column-width/ Dim iCounter As Long With Worksheets("Column width").Range("L5") For iCounter = 1 To 3 .columnWidth = Application.CentimetersToPoints(1) * (.columnWidth / .Width) Next iCounter End With End Sub
Effects of Executing Macro Example
The following GIF illustrates the results of executing this macro example. As expected, VBA sets the width of column L to 1 centimeter.
Return to VBA Code Examples
In this Article
- Set Column Width with VBA
- Set Row Height with VBA
- Autofit Column Width
- Autofit Row Height
- Set Cell Width
- Set Cell Height
- Obtain Column Width
- Obtain Row Height
- VBA Coding Made Easy
This tutorial will demonstrate how to set row height and column widths using VBA.
Excel Row heights and Columns widths can be changed in VBA by setting the .RowHeight and .ColumnWidth properties.
Set Column Width with VBA
Macro to set the column width of Columns A to E:
Sub Column_Width()
Columns("A:E").ColumnWidth = 30
End Sub
Set Row Height with VBA
Macro to set the row height of Row 1:
Sub RowHeight()
Rows("1:1").RowHeight = 30
End Sub
Autofit Column Width
Excel offers the ability to “Autofit” column widths. This feature adjusts the column width so that the column(s) is wide enough to fit all text found in that column.
To Autofit column widths in VBA:
Columns("A:B").Autofit
We wrote more about this in another article on how to Autofit a Column from VBA, including how to Autofit all used columns.
Autofit Row Height
You can also autofit row heights using a similar method:
Rows("1:2").Autofit
Set Cell Width
You can also adjust column widths by referencing a cell:
Range("a1").EntireColumn.ColumnWidth = 20
Set Cell Height
Or adjust row heights by referencing a cell:
Range("a1").EntireRow.RowHeight = 10
Obtain Column Width
To obtain the column width of a column:
dim iColumnWidth as long
iColumnWidth = columns("a").ColumnWidth
Note: This will return Null if all columns in the range do not have the same width.
Obtain Row Height
Similarly, you can obtain the row height:
dim iRowHeight as long
iRowHeight = rows("1").RowHeight
VBA Coding Made Easy
Stop searching for VBA code online. Learn more about AutoMacro – A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
Learn More!
<<Return to VBA Examples
Change Row Height and Column Width using Excel VBA
4 Comments
-
Koert penne
March 29, 2016 at 2:35 PM — ReplyI wanted the row height for content of one column, regardsless what was in the other columns. I did it as follows:
Sub rowheight_one_column()
Column = InputBox(“Hoeveelste kolom?”) + 0
Rows(20).Delete
For x = 4 To 13
Cells(20, Column) = Cells(x, Column)
Rows(20).AutoFit
hoogte = Cells(20, Column).RowHeight
Rows(x).RowHeight = hoogte
Next xRows(20).Delete
End Sub
-
Sathish
October 26, 2016 at 11:39 AM — ReplyPlease help me for auto fit the entire sheet1
-
Jack
February 21, 2017 at 7:43 PM — Replywhere have you declared your Variables, It does confuse people when your code is not neat and is exposed on the Internet where everybody does search and get stuck.
-
dskar
April 13, 2017 at 7:10 AM — Replythe difference between writing the code in code window and a module?
Effectively Manage Your
Projects and Resources
ANALYSISTABS.COM provides free and premium project management tools, templates and dashboards for effectively managing the projects and analyzing the data.
We’re a crew of professionals expertise in Excel VBA, Business Analysis, Project Management. We’re Sharing our map to Project success with innovative tools, templates, tutorials and tips.
Project Management
Excel VBA
Download Free Excel 2007, 2010, 2013 Add-in for Creating Innovative Dashboards, Tools for Data Mining, Analysis, Visualization. Learn VBA for MS Excel, Word, PowerPoint, Access, Outlook to develop applications for retail, insurance, banking, finance, telecom, healthcare domains.
Page load link
Go to Top
Содержание
- Свойство ColumnWidths
- Синтаксис
- Settings
- Замечания
- См. также
- Поддержка и обратная связь
- VBA Set Column Width or Row Height
- Set Column Width with VBA
- Set Row Height with VBA
- Autofit Column Width
- Autofit Row Height
- Set Cell Width
- Set Cell Height
- Obtain Column Width
- Obtain Row Height
- VBA Coding Made Easy
- VBA Code Examples Add-in
- Excel VBA Column Width: Step-by-Step Guide and 8 Code Examples to Set or AutoFit the Column Width with Macros
- Related VBA and Macro Tutorials
- #1: Set Column Width
- VBA Code to Set Column Width
- Process Followed by VBA Code
- VBA Statement Explanation
- Macro Example
- Effects of Executing Macro Example
- #2: Set Column Width for Multiple Contiguous Columns
- VBA Code to Set Column Width for Multiple Contiguous Columns
- Process Followed by VBA Code
- VBA Statement Explanation
- Macro Example
- Effects of Executing Macro Example
- #3: Set Column Width for Multiple Non-Contiguous Columns
- VBA Code to Set Column Width for Multiple Non-Contiguous Columns
- Process Followed by VBA Code
- VBA Statement Explanation
- Macro Example
- Effects of Executing Macro Example
- #4: AutoFit Column Width Based on Entire Column
- VBA Code to AutoFit Column Width Based on Entire Column
- Process Followed by VBA Code
- VBA Statement Explanation
- Macro Example
- Effects of Executing Macro Example
- #5: AutoFit Column Width Based on Specific Cell
- VBA Code to AutoFit Column Width Based on Specific Cell
- Process Followed by VBA Code
- VBA Statement Explanation
- Macro Example
- Effects of Executing Macro Example
- #6: Set Column Width in Points
- VBA Code to Set Column Width in Points
- Process Followed by VBA Code
- VBA Statement Explanation
- Lines #1 and #5: With Worksheet.Range(“A1CellReference”) | End With
- Lines #2 and #4: For Counter = 1 To 3 | Next Counter
- Line #3: .ColumnWidth = ColumnWidthPoints * (.ColumnWidth / .Width)
- Macro Example
- Effects of Executing Macro Example
- #7: Set Column Width in Inches
- VBA Code to Set Column Width in Inches
- Process Followed by VBA Code
- VBA Statement Explanation
- Lines #1 and #5: With Worksheet.Range(“A1CellReference”) | End With
- Lines #2 and #4: For Counter = 1 To 3 | Next Counter
- Line #3: .ColumnWidth = Application.InchesToPoints(ColumnWidthInches) * (.ColumnWidth / .Width)
- Macro Example
- Effects of Executing Macro Example
- #8: Set Column Width in Centimeters
- VBA Code to Set Column Width in Centimeters
- Process Followed by VBA Code
- VBA Statement Explanation
- Lines #1 and #5: With Worksheet.Range(“A1CellReference”) | End With
- Lines #2 and #4: For Counter = 1 To 3 | Next Counter
- Line #3: .ColumnWidth = Application.CentimetersToPoints(ColumnWidthCentimeters) * (.ColumnWidth / .Width)
- Macro Example
- Effects of Executing Macro Example
Свойство ColumnWidths
Указывает ширину каждого столбца в поле со списком с несколькими столбцами.
Синтаксис
object. ColumnWidths [= String ]
Синтаксис свойства ColumnWidths состоит из следующих частей:
Part | Описание |
---|---|
object | Обязательно. Допустимый объект. |
String | Необязательный параметр. Устанавливает ширину строки в точках. Параметр -1 или пустой приводит к вычисляемой ширине. Значение 0 приводит к скрытию столбца. Чтобы указать другую единицу измерения, добавьте ее. Значение больше 0 явно указывает ширину столбца. |
Settings
Чтобы отделить записи в столбцах, используйте точку с запятой (;) в качестве разделителя списка. В Windows это значение можно изменить, указав разделитель списка в разделе «Язык и региональные стандарты» панели управления Windows.
Любые или все параметры свойства ColumnWidths могут оставаться пустыми. Пустой параметр можно создать, указав разделитель без предшествующего ему значения.
Если указать -1 на странице свойств, отображаемое значение на странице свойств будет пустым.
Чтобы вычислить ширину столбца, если columnWidths пуста или -1, ширина элемента управления делится поровну между всеми столбцами списка. Если сумма указанной ширины столбцов превышает ширину элемента управления, список выравнивается по левому краю в пределах элемента управления и один или несколько крайних правых столбцов не отображаются. Чтобы просмотреть их, пользователи могут прокрутить список с помощью горизонтальной полосы прокрутки.
Минимальная вычисляемая ширина столбца составляет 72 точки (2,54 см). Чтобы создать более узкий столбец, необходимо указать точную ширину.
Если не указано другое, ширина столбца измеряется в точках. Чтобы указать другую единицу измерения, добавьте ее к значению. В следующих примерах ширина столбца указывается в нескольких единицах измерения, а также приводится описание различных способов размещения трех столбцов в поле со списком шириной 10,16 см.
Setting | Эффект |
---|---|
90;72;90 | Ширина первого столбца — 90 точек (3,18 см); ширина второго столбца — 72 точки (2,54 см); ширина третьего столбца — 90 точек. |
6 cm;0;6 cm | Ширина первого столбца — 6 см; второй столбец скрыт; ширина третьего столбца — 6 см. Так как третий столбец является частично видимым, отображается горизонтальная полоса прокрутки. |
1.5 in;0;2.5 in | Ширина первого столбца — 1,5 дюйма (3,81 см); второй столбец скрыт; ширина третьего столбца — 2,5 дюйма (6,35 см). |
2 in;;2 in | Ширина первого столбца — 2 дюйма (5,08 см); ширина второго столбца — 1 дюйм (2,54 см) (по умолчанию); ширина третьего столбца — 2 дюйма (5,08 см). Так как только половина третьего столбца является видимой, отображается горизонтальная полоса прокрутки. |
(Пусто) | Все три столбца имеют одинаковую ширину (3,38 см). |
Замечания
В поле со списком система отображает столбец, назначаемый свойством TextColumn в текстовой части элемента управления.
См. также
Поддержка и обратная связь
Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.
Источник
VBA Set Column Width or Row Height
In this Article
This tutorial will demonstrate how to set row height and column widths using VBA.
Excel Row heights and Columns widths can be changed in VBA by setting the .RowHeight and .ColumnWidth properties.
Set Column Width with VBA
Macro to set the column width of Columns A to E:
Set Row Height with VBA
Macro to set the row height of Row 1:
Autofit Column Width
Excel offers the ability to “Autofit” column widths. This feature adjusts the column width so that the column(s) is wide enough to fit all text found in that column.
To Autofit column widths in VBA:
We wrote more about this in another article on how to Autofit a Column from VBA, including how to Autofit all used columns.
Autofit Row Height
You can also autofit row heights using a similar method:
Set Cell Width
You can also adjust column widths by referencing a cell:
Set Cell Height
Or adjust row heights by referencing a cell:
Obtain Column Width
To obtain the column width of a column:
Note: This will return Null if all columns in the range do not have the same width.
Obtain Row Height
Similarly, you can obtain the row height:
VBA Coding Made Easy
Stop searching for VBA code online. Learn more about AutoMacro – A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
VBA Code Examples Add-in
Easily access all of the code examples found on our site.
Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.
Источник
Excel VBA Column Width: Step-by-Step Guide and 8 Code Examples to Set or AutoFit the Column Width with Macros
In this VBA Tutorial, you learn how to use Excel VBA to set or autofit the width of columns in a variety of circumstances.
This VBA Tutorial is accompanied by Excel workbooks containing the data and macros I use in the examples below. You can get immediate free access to these example workbooks by subscribing to the Power Spreadsheets Newsletter.
Use the following Table of Contents to navigate to the section you’re interested in.
Table of Contents
The following VBA and Macro Tutorials may help you better understand and implement the contents below:
- General VBA constructs and structures:
- Learn about using variables here.
- Learn about VBA data types here.
- Learn about R1C1 and A1 style references here.
- Practical VBA applications and macro examples:
- Learn how to work with worksheets here.
- Learn how to delete columns here.
- Learn how to hide or unhide rows and columns here.
You can find additional VBA and Macro Tutorials in the Archives.
#1: Set Column Width
VBA Code to Set Column Width
To set the width of a column with VBA, use a statement with the following structure:
Process Followed by VBA Code
Specify column width in units” width=”316″ height=”102″>
VBA Statement Explanation
- Item: Worksheet.
- VBA Construct: Workbook.Worksheets property.
- Description: Returns a Worksheet object representing the worksheet you work with.
- Item: Range(“A1CellReference”).
- VBA Construct: Worksheet.Range property.
- Description: Returns a Range object representing a cell within the column whose width you set. You specify the cell using an A1-style cell reference (A1CellReference) enclosed within quotations (“”).
- Item: ColumnWidth.
- VBA Construct: Range.ColumnWidth property.
- Description: Sets the width of the column containing the Range object returned by item #2 above.
- Item: ColumnWidthUnits.
- VBA Construct: New value of the Range.ColumnWidth property.
- Description: Specifies the width, in units, of the column containing the Range object returned by item #2 above.
- Column width isn’t measured in points, centimeters or inches. Excel measures column width units based on the size (width) of the font you use in the Normal style (for example, Calibri 11).
- Therefore, 1 unit of column width is equal to 1 character of the Normal style font. Consider the following:
- If your Normal style font is a fixed-width font, such as Courier New or Consolas, all characters have the same width.
- If your Normal style font is a proportional font, Excel considers the width of the character “0” (the number zero).
- If you explicitly declare a variable to represent ColumnWidthUnits, use a numeric data type that can handle the value you use to specify the column width in the appropriate units.
Macro Example
The following macro sets the width of column A of the worksheet named “Column width” to 15 units.
Effects of Executing Macro Example
The following GIF illustrates the results of executing this macro example. As expected, VBA sets the width of column A to 15 units.
#2: Set Column Width for Multiple Contiguous Columns
VBA Code to Set Column Width for Multiple Contiguous Columns
To set the width of multiple contiguous columns with VBA, use a statement with the following structure:
Process Followed by VBA Code
Specify column width in units” width=”312″ height=”105″>
VBA Statement Explanation
- Item: Worksheet.
- VBA Construct: Workbook.Worksheets property.
- Description: Returns a Worksheet object representing the worksheet you work with.
- Item: Range(“FirstColumnLetter:LastColumnLetter”).
- VBA Construct: Worksheet.Range property.
- Description: Returns a Range object representing the columns whose width you set. Under this syntax:
- You identify columns by the letters of their headers (FirstColumnLetter and LastColumnLetter).
- The column letters are:
- Separated by a colon (:), which allows you to set up an array.
- Enclosed within quotations (“”).
- Item: ColumnWidth.
- VBA Construct: Range.ColumnWidth property.
- Description: Sets the width of the columns returned by item #2 above.
- Item: ColumnWidthUnits.
- VBA Construct: New value of the Range.ColumnWidth property.
- Description: Specifies the width, in units, of the columns returned by item #2 above.
- Column width isn’t measured in points, centimeters or inches. Excel measures column width units based on the size (width) of the font you use in the Normal style (for example, Calibri 11).
- Therefore, 1 unit of column width is equal to 1 character of the Normal style font. Consider the following:
- If your Normal style font is a fixed-width font, such as Courier New or Consolas, all characters have the same width.
- If your Normal style font is a proportional font, Excel considers the width of the character “0” (the number zero).
- If you explicitly declare a variable to represent ColumnWidthUnits, use a numeric data type that can handle the value you use to specify the column width in the appropriate units.
Macro Example
The following macro sets the width of columns C through E (C, D and E) of the worksheet named “Column width” to 10 units.
Effects of Executing Macro Example
The following GIF illustrates the results of executing this macro example. As expected, VBA sets the width of columns C through E to 10 units.
#3: Set Column Width for Multiple Non-Contiguous Columns
VBA Code to Set Column Width for Multiple Non-Contiguous Columns
To set the width of multiple non-contiguous columns with VBA, use a statement with the following structure:
Process Followed by VBA Code
Specify column width in units” width=”312″ height=”105″>
VBA Statement Explanation
- Item: Worksheet.
- VBA Construct: Workbook.Worksheets property.
- Description: Returns a Worksheet object representing the worksheet you work with.
- Item:Range(“Column1Area1Letter:ColumnLastArea1Letter,Column1Area2Letter:ColumnLastArea2Letter, … , Column1AreaLastLetter:ColumnLastAreaLastLetter”).
- VBA Construct: Worksheet.Range property.
- Description: Returns a Range object representing the columns whose width you set. Under this syntax:
- You identify columns by the letters of their headers (Column1Area1Letter, ColumnLastArea1Letter, Column1Area2Letter, ColumnLastArea2Letter, … , Column1AreaLastLetter and ColumnLastAreaLastLetter”).
- The column letters identifying contiguous columns (within the same data area) are separated by a colon (:), which allows you to set up an array. If you’re only referring to a single column (for example, column B), include the letter reference twice and separate them with a colon (:) (for example “B:B”).
- The column letters identifying non-contiguous columns (in separate data areas) are separated by the union operator, a comma (,).
- The complete column reference is enclosed within quotations (“”).
- Item: ColumnWidth.
- VBA Construct: Range.ColumnWidth property.
- Description: Sets the width of the columns returned by item #2 above.
- Item: ColumnWidthUnits.
- VBA Construct: New value of the Range.ColumnWidth property.
- Description: Specifies the width, in units, of the columns returned by item #2 above.
- Column width isn’t measured in points, centimeters or inches. Excel measures column width units based on the size (width) of the font you use in the Normal style (for example, Calibri 11).
- Therefore, 1 unit of column width is equal to 1 character of the Normal style font. Consider the following:
- If your Normal style font is a fixed-width font, such as Courier New or Consolas, all characters have the same width.
- If your Normal style font is a proportional font, Excel considers the width of the character “0” (the number zero).
- If you explicitly declare a variable to represent ColumnWidthUnits, use a numeric data type that can handle the value you use to specify the column width in the appropriate units.
Macro Example
The following macro sets the width of columns B, F and H of the worksheet named “Column width” to 20 units.
Effects of Executing Macro Example
The following GIF illustrates the results of executing this macro example. As expected, VBA sets the width of columns B, F and H to 20 units.
#4: AutoFit Column Width Based on Entire Column
VBA Code to AutoFit Column Width Based on Entire Column
To autofit the width of a column with VBA, considering the contents of the entire column, use a statement with the following structure:
Process Followed by VBA Code
return entire column > autofit entire column width” width=”497″ height=”107″>
VBA Statement Explanation
- Item: Worksheet.
- VBA Construct: Workbook.Worksheets property.
- Description: Returns a Worksheet object representing the worksheet you work with.
- Item: Range(“A1CellReference”).
- VBA Construct: Worksheet.Range property.
- Description: Returns a Range object representing a cell within the column you autofit. You specify the cell using an A1-style cell reference (A1CellReference) enclosed within quotations (“”).
- Item: EntireColumn.
- VBA Construct: Range.EntireColumn property.
- Description: Returns a Range object representing the entire column containing the Range object returned by item #2 above.
- Item: AutoFit.
- VBA Construct: Range.AutoFit method.
- Description: Modifies the width of the column represented by the Range object returned by item #3 above to achieve the best fit (autofits).
Macro Example
The following macro autofits the width of column G of the worksheet named “Column width” based on the contents of all the cells in the entire column.
Effects of Executing Macro Example
The following GIF illustrates the results of executing this macro example. As expected, VBA autofits the width of column G based on the contents of all the cells in the entire column. Notice the contents in cell G10 (Autofit based on entire column), which are used as the basis for the autofitting operation.
#5: AutoFit Column Width Based on Specific Cell
VBA Code to AutoFit Column Width Based on Specific Cell
To autofit the width of a column with VBA, considering the contents of a specific cell or row, use a statement with the following structure:
Process Followed by VBA Code
return column > autofit entire column width to contents of cell” width=”493″ height=”105″>
VBA Statement Explanation
- Item: Worksheet.
- VBA Construct: Workbook.Worksheets property.
- Description: Returns a Worksheet object representing the worksheet you work with.
- Item: Range(“A1CellReference”).
- VBA Construct: Worksheet.Range property.
- Description: Returns a Range object representing a cell.
- This cell:
- Is within the column you autofit.
- Is the cell whose contents Excel considers for purposes of achieving the best fit (autofitting).
- You specify the cell using an A1-style cell reference (A1CellReference) enclosed within quotations (“”).
- This cell:
- Item: Columns.
- VBA Construct: Range.Columns property.
- Description: Returns a Range object representing the column containing the Range object returned by item #2 above.
- Item: AutoFit.
- VBA Construct: Range.AutoFit method.
- Description: Modifies the width of the column represented by the Range object returned by item #3 above to achieve the best fit (autofits) based on the contents within the cell represented by the Range object returned by item #2 above.
Macro Example
The following macro autofits the width of column I of the worksheet named “Column width” based on the contents of cell I5.
Effects of Executing Macro Example
The following GIF illustrates the results of executing this macro example. As expected, VBA sets autofits the width of column I based on the contents of cell I5. Notice the contents in cell I10 (Autofit based on specific cell), which aren’t used as the basis for the autofitting operation.
#6: Set Column Width in Points
VBA Code to Set Column Width in Points
To set the width of a column in points with VBA, use a macro with the following statement structure:
Process Followed by VBA Code
specify column width in points 3 times” width=”689″ height=”192″>
VBA Statement Explanation
Lines #1 and #5: With Worksheet.Range(“A1CellReference”) | End With
- Item: With… End With.
- VBA Construct: With… End With statement.
- Description: Statements within the With… End With statement (lines # through #4 below) are executed on the Range object returned by item #3 below.
- Item: Worksheet.
- VBA Construct: Workbook.Worksheets property.
- Description: Returns a Worksheet object representing the worksheet you work with.
- Item: Range(“A1CellReference”).
- VBA Construct: Worksheet.Range property.
- Description: Returns a Range object representing a cell within the column whose width you set. You specify the cell using an A1-style cell reference (A1CellReference) enclosed within quotations (“”).
Lines #2 and #4: For Counter = 1 To 3 | Next Counter
- Item: For… Next Counter.
- VBA Construct: For… Next statement.
- Description: Repeats the statement within the loop (line #3 below) 3 times, as required by item #3 below.
- Item: Counter.
- VBA Construct: Counter of For… Next statement.
- Description: Loop counter. If you explicitly declare a variable to represent the loop counter, use the Long data type.
- Item: 1 To 3.
- VBA Construct: Counter Start (1) and Counter End (3) of For… Next statement.
- Description: The statement within the loop (line #3 below) is executed 3 times (1 To 3).
- Theoretically, line #3 below should be enough to set the column width in points without requiring the loop specified by these lines #2 and #4. In practice, this may not be the case. Some tests suggest that repeating line #3 below (or similar) 3 times generally gets you the closest to the specified column width.
Line #3: .ColumnWidth = ColumnWidthPoints * (.ColumnWidth / .Width)
- Item: .ColumnWidth.
- VBA Construct: Range.ColumnWidth property.
- Description:
- Sets the width of the column containing the Range object within the opening statement of the With… End With block (line #1, item #3 above).
- .ColumnWidth is included twice in the statement. In this first mention, (.ColumnWidth = …), ColumnWidth is the property to which a value is assigned. The value assigned to the ColumnWidth property is the value returned by the other items within this statement.
- Item: ColumnWidthPoints.
- VBA Construct: Numeric (for example, Double) variable.
- Description: Specifies the width (in points) of the columns containing the Range object within the opening statement of the With… End With block (line #1, item #3 above).
- If you explicitly declare a variable to represent ColumnWidthPoints, use a numeric data type that can handle the value you use to specify the column width in points.
- Item: .ColumnWidth.
- VBA Construct: Range.ColumnWidth property.
- Description:
- Returns the width of the column containing the Range object within the opening statement of the With… End With block (line #1, item #3 above).
- .ColumnWidth is included twice in the statement. In this second mention, (.ColumnWidth), ColumnWidth returns the current value of the property.
- The ColumnWidth property returns the column width in units based on the size (width) of the font you use in the Normal style (for example, Calibri 11). Therefore, 1 unit of column width is equal to 1 character of the Normal style font. If your Normal style font is a proportional (not fixed-width) font, Excel considers the width of the character “0” (the number zero).
- Item: .Width.
- VBA Construct: Range.Width property.
- Description:
- Returns the width of the column containing the Range object within the opening statement of the With… End With block (line #1, item #3 above).
- The Width property returns the column width in points.
- Item: (.ColumnWidth / .Width).
- VBA Construct: Numeric expression.
- Description:
- Both ColumnWidth (item #3 above) and Width (item #4 above) return the width of the column containing the Range object within the opening statement of the With… End With block (line #1, item #3 above).
- The units in which ColumnWidth and Width return the column width differ.
- ColumnWidth expresses the column width in units based on the size (width) of the font you use in the Normal style.
- Width expresses the column width in points.
- ColumnWidth divided by Width (.ColumnWidth / .Width) returns the factor by which you must multiply the desired column width expressed in points (item #2 above) to obtain the appropriate column width in units based on the size (width) of the font you use in the Normal style. In other words, this expression converts ColumnWidthPoints from points to the units required by the ColumnWidth property.
Macro Example
The following macro sets the width of column J of the worksheet named “Column width” to 80 points.
Effects of Executing Macro Example
The following GIF illustrates the results of executing this macro example. As expected, VBA sets the width of column J to 80 points.
#7: Set Column Width in Inches
VBA Code to Set Column Width in Inches
To set the width of a column in inches with VBA, use a macro with the following statement structure:
Process Followed by VBA Code
specify column width in inches 3 times” width=”686″ height=”191″>
VBA Statement Explanation
Lines #1 and #5: With Worksheet.Range(“A1CellReference”) | End With
- Item: With… End With.
- VBA Construct: With… End With statement.
- Description: Statements within the With… End With statement (lines # through #4 below) are executed on the Range object returned by item #3 below.
- Item: Worksheet.
- VBA Construct: Workbook.Worksheets property.
- Description: Returns a Worksheet object representing the worksheet you work with.
- Item: Range(“A1CellReference”).
- VBA Construct: Worksheet.Range property.
- Description: Returns a Range object representing a cell within the column whose width you set. You specify the cell using an A1-style cell reference (A1CellReference) enclosed within quotations (“”).
Lines #2 and #4: For Counter = 1 To 3 | Next Counter
- Item: For… Next Counter.
- VBA Construct: For… Next statement.
- Description: Repeats the statement within the loop (line #3 below) 3 times, as required by item #3 below.
- Item: Counter.
- VBA Construct: Counter of For… Next statement.
- Description: Loop counter. If you explicitly declare a variable to represent the loop counter, use the Long data type.
- Item: 1 To 3.
- VBA Construct: Counter Start (1) and Counter End (3) of For… Next statement.
- Description: The statement within the loop (line #3 below) is executed 3 times (1 To 3).
- Theoretically, line #3 below should be enough to set the column width in inches without requiring the loop specified by these lines #2 and #4. In practice, this may not be the case. Some tests suggest that repeating line #3 below (or similar) 3 times generally gets you the closest to the specified column width.
Line #3: .ColumnWidth = Application.InchesToPoints(ColumnWidthInches) * (.ColumnWidth / .Width)
- Item: .ColumnWidth.
- VBA Construct: Range.ColumnWidth property.
- Description:
- Sets the width of the column containing the Range object within the opening statement of the With… End With block (line #1, item #3 above).
- .ColumnWidth is included twice in the statement. In this first mention, (.ColumnWidth = …), ColumnWidth is the property to which a value is assigned. The value assigned to the ColumnWidth property is the value returned by the other items within this statement.
- Item: Application.InchesToPoints.
- VBA Construct: Application.InchesToPoints method.
- Description: Converts the measurement specified by item #3 below from inches to points.
- Item: ColumnWidthInches.
- VBA Construct: Inches parameter of Application.InchesToPoints method.
- Description: Specifies the width (in inches) of the columns containing the Range object within the opening statement of the With… End With block (line #1, item #3 above).
- If you explicitly declare a variable to represent ColumnWidthInches, use a numeric data type that can handle the value you use to specify the column width in inches.
- Item: .ColumnWidth.
- VBA Construct: Range.ColumnWidth property.
- Description:
- Returns the width of the column containing the Range object within the opening statement of the With… End With block (line #1, item #3 above).
- .ColumnWidth is included twice in the statement. In this second mention, (.ColumnWidth), ColumnWidth returns the current value of the property.
- The ColumnWidth property returns the column width in units based on the size (width) of the font you use in the Normal style (for example, Calibri 11). Therefore, 1 unit of column width is equal to 1 character of the Normal style font. If your Normal style font is a proportional (not fixed-width) font, Excel considers the width of the character “0” (the number zero).
- Item: .Width.
- VBA Construct: Range.Width property.
- Description:
- Returns the width of the column containing the Range object within the opening statement of the With… End With block (line #1, item #3 above).
- The Width property returns the column width in points.
- Item: (.ColumnWidth / .Width).
- VBA Construct: Numeric expression.
- Description:
- Both ColumnWidth (item #4 above) and Width (item #5 above) return the width of the column containing the Range object within the opening statement of the With… End With block (line #1, item #3 above).
- The units in which ColumnWidth and Width return the column width differ.
- ColumnWidth expresses the column width in units based on the size (width) of the font you use in the Normal style.
- Width expresses the column width in points.
- ColumnWidth divided by Width (.ColumnWidth / .Width) returns the factor by which you must multiply the desired column width expressed in inches/points (items #2 and #3 above) to obtain the appropriate column width in units based on the size (width) of the font you use in the Normal style. In other words, this expression converts Application.InchesToPoints(ColumnWidthInches) from points to the units required by the ColumnWidth property.
Macro Example
The following macro sets the width of column K of the worksheet named “Column width” to 1 inch.
Effects of Executing Macro Example
The following GIF illustrates the results of executing this macro example. As expected, VBA sets the width of column K to 1 inch.
#8: Set Column Width in Centimeters
VBA Code to Set Column Width in Centimeters
To set the width of a column in centimeters with VBA, use a macro with the following statement structure:
Process Followed by VBA Code
specify column width in centimeters 3 times” width=”683″ height=”192″>
VBA Statement Explanation
Lines #1 and #5: With Worksheet.Range(“A1CellReference”) | End With
- Item: With… End With.
- VBA Construct: With… End With statement.
- Description: Statements within the With… End With statement (lines # through #4 below) are executed on the Range object returned by item #3 below.
- Item: Worksheet.
- VBA Construct: Workbook.Worksheets property.
- Description: Returns a Worksheet object representing the worksheet you work with.
- Item: Range(“A1CellReference”).
- VBA Construct: Worksheet.Range property.
- Description: Returns a Range object representing a cell within the column whose width you set. You specify the cell using an A1-style cell reference (A1CellReference) enclosed within quotations (“”).
Lines #2 and #4: For Counter = 1 To 3 | Next Counter
- Item: For… Next Counter.
- VBA Construct: For… Next statement.
- Description: Repeats the statement within the loop (line #3 below) 3 times, as required by item #3 below.
- Item: Counter.
- VBA Construct: Counter of For… Next statement.
- Description: Loop counter. If you explicitly declare a variable to represent the loop counter, use the Long data type.
- Item: 1 To 3.
- VBA Construct: Counter Start (1) and Counter End (3) of For… Next statement.
- Description: The statement within the loop (line #3 below) is executed 3 times (1 To 3).
- Theoretically, line #3 below should be enough to set the column width in centimeters without requiring the loop specified by these lines #2 and #4. In practice, this may not be the case. Some tests suggest that repeating line #3 below (or similar) 3 times generally gets you the closest to the specified column width.
Line #3: .ColumnWidth = Application.CentimetersToPoints(ColumnWidthCentimeters) * (.ColumnWidth / .Width)
- Item: .ColumnWidth.
- VBA Construct: Range.ColumnWidth property.
- Description:
- Sets the width of the column containing the Range object within the opening statement of the With… End With block (line #1, item #3 above).
- .ColumnWidth is included twice in the statement. In this first mention, (.ColumnWidth = …), ColumnWidth is the property to which a value is assigned. The value assigned to the ColumnWidth property is the value returned by the other items within this statement.
- Item: Application.CentimetersToPoints.
- VBA Construct: Application.CentimetersToPoints method.
- Description: Converts the measurement specified by item #3 below from centimeters to points.
- Item: ColumnWidthCentimeters.
- VBA Construct: Centimeters parameter of Application.CentimetersToPoints method.
- Description: Specifies the width (in centimeters) of the columns containing the Range object within the opening statement of the With… End With block (line #1, item #3 above).
- If you explicitly declare a variable to represent ColumnWidthCentimeters, use a numeric data type that can handle the value you use to specify the column width in centimeters.
- Item: .ColumnWidth.
- VBA Construct: Range.ColumnWidth property.
- Description:
- Returns the width of the column containing the Range object within the opening statement of the With… End With block (line #1, item #3 above).
- .ColumnWidth is included twice in the statement. In this second mention, (.ColumnWidth), ColumnWidth returns the current value of the property.
- The ColumnWidth property returns the column width in units based on the size (width) of the font you use in the Normal style (for example, Calibri 11). Therefore, 1 unit of column width is equal to 1 character of the Normal style font. If your Normal style font is a proportional (not fixed-width) font, Excel considers the width of the character “0” (the number zero).
- Item: .Width.
- VBA Construct: Range.Width property.
- Description:
- Returns the width of the column containing the Range object within the opening statement of the With… End With block (line #1, item #3 above).
- The Width property returns the column width in points.
- Item: (.ColumnWidth / .Width).
- VBA Construct: Numeric expression.
- Description:
- Both ColumnWidth (item #4 above) and Width (item #5 above) return the width of the column containing the Range object within the opening statement of the With… End With block (line #1, item #3 above).
- The units in which ColumnWidth and Width return the column width differ.
- ColumnWidth expresses the column width in units based on the size (width) of the font you use in the Normal style.
- Width expresses the column width in points.
- ColumnWidth divided by Width (.ColumnWidth / .Width) returns the factor by which you must multiply the desired column width expressed in centimeters/points (items #2 and #3 above) to obtain the appropriate column width in units based on the size (width) of the font you use in the Normal style. In other words, this expression converts Application.CentimetersToPoints(ColumnWidthCentimeters) from points to the units required by the ColumnWidth property.
Macro Example
The following macro sets the width of column L of the worksheet named “Column width” to 1 centimeter.
Effects of Executing Macro Example
The following GIF illustrates the results of executing this macro example. As expected, VBA sets the width of column L to 1 centimeter.
Источник
Изменение размера ячейки в VBA Excel. Высота строки, ширина столбца, автоподбор ширины ячейки. Свойства RowHeight и ColumnWidth объекта Range.
Размер ячейки
Размер ячейки по высоте и ширине определяется высотой строки и шириной столбца, на пересечении которых она находится. Если, в вашем случае, нежелательно изменять размеры всей строки или всего столбца, используйте объединенные ячейки нужной величины.
Обратите внимание, что высота строки задается в пунктах, а ширина столбца в символах, поэтому их числовые значения не соответствуют друг другу по фактическому размеру.
Высота строки и ширина столбца в Excel
Программно, без дополнительных макросов, можно изменять высоту строки только в пунктах, а ширину столбца только в символах.
На сайте поддержки офисных приложений Microsoft так написано об этих величинах:
- высота строки может принимать значение от 0 до 409 пунктов, причем 1 пункт приблизительно равен 1/72 дюйма или 0,035 см;
- ширина столбца может принимать значение от 0 до 255, причем это значение соответствует количеству символов, которые могут быть отображены в ячейке.
Смотрите, как сделать все ячейки рабочего листа квадратными.
Высота строки
Для изменения высоты строки используйте свойство RowHeight объекта Range. И не важно, будет объект Range представлять из себя выделенный произвольный диапазон, отдельную ячейку, целую строку или целый столбец — высота всех строк, пересекающихся с объектом Range будет изменена после присвоения свойству RowHeight этого объекта нового значения.
Примеры изменения высоты строк:
Пример 1
Изменение высоты отдельной ячейки:
ActiveCell.RowHeight = 10 |
в результате, строка, в которой находится активная ячейка, приобретает высоту, равную 10 пунктам.
Пример 2
Изменение высоты строки:
в результате, третья строка рабочего листа приобретает высоту, равную 30 пунктам.
Пример 3
Изменение высоты ячеек заданного диапазона:
Range(«A1:D6»).RowHeight = 20 |
в результате, каждой из первых шести строк рабочего листа будет задана высота, равная 20 пунктам.
Пример 4
Изменение высоты ячеек целого столбца:
Columns(5).RowHeight = 15 |
в результате, всем строкам рабочего листа будет назначена высота, равная 15 пунктам.
Ширина столбца
Для изменения ширины столбца используйте свойство ColumnWidth объекта Range. Как и в случае с высотой строки, не важно, будет объект Range представлять из себя выделенный произвольный диапазон, отдельную ячейку, целую строку или целый столбец — ширина всех столбцов, пересекающихся с объектом Range будет изменена после присвоения свойству ColumnWidth этого объекта нового значения.
Примеры изменения ширины столбцов:
Пример 1
Изменение ширины отдельной ячейки:
ActiveCell.ColumnWidth = 15 |
в результате, столбец, в котором находится активная ячейка, приобретает ширину, равную 15 символам.
Пример 2
Изменение ширины столбца:
Columns(3).ColumnWidth = 50 |
в результате, третий столбец рабочего листа (столбец «C») приобретает ширину, равную 50 символам.
Пример 3
Изменение ширины ячеек заданного диапазона:
Range(«A1:D6»).ColumnWidth = 25 |
в результате, каждому из первых четырех столбцов рабочего листа будет задана ширина, равная 25 символам.
Пример 4
Изменение ширины ячеек целой строки:
в результате, всем столбцам рабочего листа будет назначена ширина, равная 35 символам.
Автоподбор ширины
Для автоподбора ширины ячейки в соответствие с размером ее содержимого используйте следующий код:
‘запишем для примера в любую ячейку рабочего ‘листа какой-нибудь текст, например, такой: Cells(5, 5) = «Автоподбор ширины ячейки» ‘теперь подгоним ширину ячейки, а точнее ‘столбца, в котором эта ячейка находится: Cells(5, 5).EntireColumn.AutoFit |
Имейте в виду, что ширина столбца будет подогнана по расположенной в этом столбце ячейке с самым длинным содержимым. Например, если длина содержимого ячейки Cells(7, 5) будет превышать длину содержимого ячейки Cells(5, 5), то автоподбор ширины пятого столбца произойдет по содержимому ячейки Cells(7, 5), несмотря на то, что в строке кода указана другая ячейка.
Как осуществить автоподбор ширины объединенной ячейки, в которой метод AutoFit не работает, смотрите в следующей статье.