Excel vba автоподбор ширины

Изменение размера ячейки в VBA Excel. Высота строки, ширина столбца, автоподбор ширины ячейки. Свойства RowHeight и ColumnWidth объекта Range.

Размер ячейки

Размер ячейки по высоте и ширине определяется высотой строки и шириной столбца, на пересечении которых она находится. Если, в вашем случае, нежелательно изменять размеры всей строки или всего столбца, используйте объединенные ячейки нужной величины.

Обратите внимание, что высота строки задается в пунктах, а ширина столбца в символах, поэтому их числовые значения не соответствуют друг другу по фактическому размеру.

Информационные окна с высотой строки и шириной столбца в Excel

Высота строки и ширина столбца в 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 не работает, смотрите в следующей статье.

Home / VBA / VBA AutoFit (Rows, Column, or the Entire Worksheet)

Key Points

  • In VBA, you can use the AutoFit method to auto-fit rows, columns, and even an entire worksheet.
  • You need to specify the range, and then you can use the AutoFit method.

Let’s say you want to autofit column A, the code would be something like below:

Range("A1").EntireColumn.AutoFit

In the above line of code, you have used the EntireColumn property to refer to the entire column of cell A1.

As you are within a worksheet so you can also use the columns property and write a code like the below.

Columns(1).AutoFit

AutoFit a Row

In the same way, you can write code to autofit a row. Let’s say you want to autofit row 5, the code would be:

Range("A5").EntireRow.AutoFit

And if you want to use the row property, then you can use the code like the following.

Rows(5).AutoFit

AutoFit UsedRange (Rows and Columns)

Now let’s say, you only want to autofit those columns and rows where you have data. In VBA, there is a property called used range that you can use. So the code would be.

ActiveSheet.UsedRange.EntireColumn.AutoFit

ActiveSheet.UsedRange.EntireRow.AutoFit

And if you want to use a specific worksheet then the code would be.

Worksheets("Sheet1").UsedRange.EntireColumn.AutoFit
Worksheets("Sheet1").UsedRange.EntireRow.AutoFit

AutoFit Entire Worksheet

And if you want to refer to all the columns and rows of the worksheet then you can use the “CELLS” property. Here’s the code.

Worksheets("Sheet1").Cells.EntireColumn.AutoFit
Worksheets("Sheet1").Cells.EntireRow.AutoFit

Or you can also use VBA’s WITH statement to write a code like the below.

With Worksheets("Sheet1").Cells
    .EntireColumn.AutoFit
    .EntireRow.AutoFit
End With

More Tutorials

    • Count Rows using VBA in Excel
    • Excel VBA Font (Color, Size, Type, and Bold)
    • Excel VBA Hide and Unhide a Column or a Row
    • Excel VBA Range – Working with Range and Cells in VBA
    • Apply Borders on a Cell using VBA in Excel
    • Find Last Row, Column, and Cell using VBA in Excel
    • Insert a Row using VBA in Excel
    • Merge Cells in Excel using a VBA Code
    • Select a Range/Cell using VBA in Excel
    • SELECT ALL the Cells in a Worksheet using a VBA Code
    • ActiveCell in VBA in Excel
    • Special Cells Method in VBA in Excel
    • UsedRange Property in VBA in Excel
    • VBA ClearContents (from a Cell, Range, or Entire Worksheet)
    • VBA Copy Range to Another Sheet + Workbook
    • VBA Enter Value in a Cell (Set, Get and Change)
    • VBA Insert Column (Single and Multiple)
    • VBA Named Range | (Static + from Selection + Dynamic)
    • VBA Range Offset
    • VBA Sort Range | (Descending, Multiple Columns, Sort Orientation
    • VBA Wrap Text (Cell, Range, and Entire Worksheet)
    • VBA Check IF a Cell is Empty + Multiple Cells

    ⇠ Back to What is VBA in Excel

    Helpful Links – Developer Tab – Visual Basic Editor – Run a Macro – Personal Macro Workbook – Excel Macro Recorder – VBA Interview Questions – VBA Codes

    ГЛАВНАЯ

    ТРЕНИНГИ

       Быстрый старт
       Расширенный Excel
       Мастер Формул
       Прогнозирование
       Визуализация
       Макросы на VBA

    КНИГИ

       Готовые решения
       Мастер Формул
       Скульптор данных

    ВИДЕОУРОКИ

    ПРИЕМЫ

       Бизнес-анализ
       Выпадающие списки
       Даты и время
       Диаграммы
       Диапазоны
       Дубликаты
       Защита данных
       Интернет, email
       Книги, листы
       Макросы
       Сводные таблицы
       Текст
       Форматирование
       Функции
       Всякое
    PLEX

       Коротко
       Подробно
       Версии
       Вопрос-Ответ
       Скачать
       Купить

    ПРОЕКТЫ

    ОНЛАЙН-КУРСЫ

    ФОРУМ

       Excel
       Работа
       PLEX

    © Николай Павлов, Planetaexcel, 2006-2022
    info@planetaexcel.ru


    Использование любых материалов сайта допускается строго с указанием прямой ссылки на источник, упоминанием названия сайта, имени автора и неизменности исходного текста и иллюстраций.

    Техническая поддержка сайта

    ООО «Планета Эксел»

    ИНН 7735603520


    ОГРН 1147746834949
            ИП Павлов Николай Владимирович
            ИНН 633015842586
            ОГРНИП 310633031600071 

    Excel VBA Tutorial about Column Width Setting or AutofittingIn 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

    Identify cell in column to set width for data-lazy-srcset= Specify column width in units” width=”316″ height=”102″>

    VBA Statement Explanation

    1. Item: Worksheet.
      • VBA Construct: Workbook.Worksheets property.
      • Description: Returns a Worksheet object representing the worksheet you work with.
    2. 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 (“”).
    3. Item: ColumnWidth.
      • VBA Construct: Range.ColumnWidth property.
      • Description: Sets the width of the column containing the Range object returned by item #2 above.
    4. 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.

    Macro sets column width

    #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

    Identify columns to set width for data-lazy-srcset= Specify column width in units” width=”312″ height=”105″>

    VBA Statement Explanation

    1. Item: Worksheet.
      • VBA Construct: Workbook.Worksheets property.
      • Description: Returns a Worksheet object representing the worksheet you work with.
    2. 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 (“”).
    3. Item: ColumnWidth.
      • VBA Construct: Range.ColumnWidth property.
      • Description: Sets the width of the columns returned by item #2 above.
    4. 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.

    Macro sets column width for multiple columns

    #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

    Identify columns to set width for data-lazy-srcset= Specify column width in units” width=”312″ height=”105″>

    VBA Statement Explanation

    1. Item: Worksheet.
      • VBA Construct: Workbook.Worksheets property.
      • Description: Returns a Worksheet object representing the worksheet you work with.
    2. 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 (“”).
    3. Item: ColumnWidth.
      • VBA Construct: Range.ColumnWidth property.
      • Description: Sets the width of the columns returned by item #2 above.
    4. 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.

    Macro sets column width for multiple non-contiguous columns

    #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

    Identify cell data-lazy-srcset= return entire column > autofit entire column width” width=”497″ height=”107″>

    VBA Statement Explanation

    1. Item: Worksheet.
      • VBA Construct: Workbook.Worksheets property.
      • Description: Returns a Worksheet object representing the worksheet you work with.
    2. 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 (“”).
    3. 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.
    4. 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.

    Macro autofits column width based on entire column

    #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

    Identify cell data-lazy-srcset= return column > autofit entire column width to contents of cell” width=”493″ height=”105″>

    VBA Statement Explanation

    1. Item: Worksheet.
      • VBA Construct: Workbook.Worksheets property.
      • Description: Returns a Worksheet object representing the worksheet you work with.
    2. 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 (“”).
    3. Item: Columns.
      • VBA Construct: Range.Columns property.
      • Description: Returns a Range object representing the column containing the Range object returned by item #2 above.
    4. 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.

    Macro autofits column width based on cell contents

    #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

    Identify cell data-lazy-srcset= specify column width in points 3 times” width=”689″ height=”192″>

    VBA Statement Explanation

    Lines #1 and #5: With Worksheet.Range(“A1CellReference”) | End With

    1. 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.
    2. Item: Worksheet.
      • VBA Construct: Workbook.Worksheets property.
      • Description: Returns a Worksheet object representing the worksheet you work with.
    3. 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

    1. 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.
    2. 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.
    3. 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)

    1. 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.
    2. 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.
    3. 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).
    4. 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.
    5. 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.

    Macro sets column width in 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

    Identify cell data-lazy-srcset= specify column width in inches 3 times” width=”686″ height=”191″>

    VBA Statement Explanation

    Lines #1 and #5: With Worksheet.Range(“A1CellReference”) | End With

    1. 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.
    2. Item: Worksheet.
      • VBA Construct: Workbook.Worksheets property.
      • Description: Returns a Worksheet object representing the worksheet you work with.
    3. 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

    1. 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.
    2. 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.
    3. 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)

    1. 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.
    2. Item: Application.InchesToPoints.
      • VBA Construct: Application.InchesToPoints method.
      • Description: Converts the measurement specified by item #3 below from inches to points.
    3. 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.
    4. 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).
    5. 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.
    6. 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.

    Macro sets column width in inches

    #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

    Identify cell data-lazy-srcset= specify column width in centimeters 3 times” width=”683″ height=”192″>

    VBA Statement Explanation

    Lines #1 and #5: With Worksheet.Range(“A1CellReference”) | End With

    1. 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.
    2. Item: Worksheet.
      • VBA Construct: Workbook.Worksheets property.
      • Description: Returns a Worksheet object representing the worksheet you work with.
    3. 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

    1. 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.
    2. 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.
    3. 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)

    1. 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.
    2. Item: Application.CentimetersToPoints.
      • VBA Construct: Application.CentimetersToPoints method.
      • Description: Converts the measurement specified by item #3 below from centimeters to points.
    3. 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.
    4. 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).
    5. 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.
    6. 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.

    Macro sets column width in centimeters

    Содержание

    1. Подбор высоты строки/ширины столбца объединенной ячейки
    2. VBA Excel. Автоподбор ширины объединенной ячейки
    3. Автоподбор ширины ячейки
    4. Обработка списка ячеек
    5. Автоподбор ширины столбца excel vba

    Подбор высоты строки/ширины столбца объединенной ячейки

    Для начала немного теории. Если в ячейках листа Excel записан некий длинный текст, то обычно устанавливают перенос на строки(вкладка Главная -группа ВыравниваниеПеренос текста), чтобы текст не растягивался на весь экран, а умещался в ячейке. При этом высота ячейки тоже должна измениться, чтобы отобразить все содержимое. Если речь идет всего об одной простой ячейке — проблем не возникает. Обычно, чтобы установить высоту строки на основании содержимого ячейки, достаточно навести курсор мыши в заголовке строк на границу строки(курсор приобретет вид направленных в разные стороны стрелок — ) и дважды быстро щелкнуть левой кнопкой мыши. Тоже самое можно сделать и для ширины столбцов.
    Но с объединенными ячейками такой фокус не прокатывает — ширина и высота для этих ячеек так не подбирается, сколько ни щелкай и приходится вручную подгонять каждую, чтобы текст ячейки отображался полностью:

    Стандартными средствами такой автоподбор не сделать, но вот при помощи VBA — без проблем. Ниже приведена функция, которая поможет подобрать высоту и ширину объединенных ячеек на основании их содержимого.

    ‘————————————————————————————— ‘ Procedure : RowHeightForContent ‘ Author : The_Prist(Щербаков Дмитрий) ‘ http://www.excel-vba.ru ‘ Purpose : Функция подбирает высоту строки/ширину столбца объединенных ячеек по содержимому ‘————————————————————————————— Function RowColHeightForContent(rc As Range, Optional bRowHeight As Boolean = True) ‘rc — ячейка, высоту строки или ширину столбца которой необходимо подобрать ‘bRowHeight — True — если необходимо подобрать высоту строки ‘ False — если необходимо подобрать ширину столбца Dim OldR_Height As Single, OldC_Widht As Single Dim MergedR_Height As Single, MergedC_Widht As Single Dim CurrCell As Range Dim ih As Integer Dim iw As Integer Dim NewR_Height As Single, NewC_Widht As Single Dim ActiveCellHeight As Single If rc.MergeCells Then With rc.MergeArea ‘если ячейка объединена ‘запоминаем кол-во столбцов iw = .Columns(.Columns.Count).Column — rc.Column + 1 ‘запоминаем кол-во строк. ih = .Rows(.Rows.Count).Row — rc.Row + 1 ‘Определяем высоту и ширину объединения ячеек MergedR_Height = 0 For Each CurrCell In .Rows MergedR_Height = CurrCell.RowHeight + MergedR_Height Next MergedC_Widht = 0 For Each CurrCell In .Columns MergedC_Widht = CurrCell.ColumnWidth + MergedC_Widht Next ‘запоминаем высоту и ширину первой ячейки из объединенных OldR_Height = .Cells(1, 1).RowHeight OldC_Widht = .Cells(1, 1).ColumnWidth ‘отменяем объединение ячеек .MergeCells = False ‘назначаем новую высоту и ширину для первой ячейки .Cells(1).RowHeight = MergedR_Height .Cells(1, 1).EntireColumn.ColumnWidth = MergedC_Widht ‘если необходимо изменить высоту строк If bRowHeight Then ‘.WrapText = True ‘раскомментировать, если необходимо принудительно выставлять перенос текста .EntireRow.AutoFit NewR_Height = .Cells(1).RowHeight ‘запоминаем высоту строки .MergeCells = True If OldR_Height ‘ .WrapText = True ‘раскомментировать, если необходимо принудительно выставлять перенос текста тогда код сам проставит переносы. Но тут следует учитывать, что в данном случае перенос будет выставлен для всех ячеек, что не всегда отвечает условиям

  • функция подбирает высоту и ширину исключительно для объединенных ячеек. Если ячейка не объединена — код оставит её без изменений
  • Теперь о том, как это работает и как применять. Для начала необходимо приведенный выше код функции вставить в стандартный модуль. Сама по себе функция работать не будет — её надо вызывать из другого кода, который определяет какие ячейки обрабатывать. В качестве такого кода я предлагаю следующий:

    Sub ChangeRowColHeight() Dim rc As Range Dim bRow As Boolean bRow = (MsgBox(«Изменять высоту строк?», vbQuestion + vbYesNo, «www.excel-vba.ru») = vbYes) ‘bRow = True: для изменения высоты строк ‘bRow = False: для изменения ширины столбцов Application.ScreenUpdating = False For Each rc In Selection RowColHeightForContent rc, bRow Next Application.ScreenUpdating = True End Sub

    Этот код также необходимо вставить в стандартный модуль. Теперь его можно будет вызвать из этой книги, нажатием клавиш Alt+F8 и выбрав ChangeRowColHeight , или создав на листе кнопку и назначив ей макрос. После этого достаточно будет выделить диапазон ячеек, среди которых есть объединенные и вызвать макрос ChangeRowColHeight. Для всех объединенных ячеек в выделенном диапазоне будет подобрана высота или ширина.
    Чтобы было нагляднее — я приложил пример, в котором помимо самих кодов есть вырезка из стандартной накладной. Именно в таких документах наиболее часто встречаются подобные казусы и необходимость подбирать высоту и ширину объединенных ячеек.
    Скачать пример:

    Tips_Macro_HeightWidthInMergeCell.xls (64,0 KiB, 3 444 скачиваний)

    Если подобную операцию приходится производить постоянно — советую коды записать в надстройку: Как создать свою надстройку?. Так же можно воспользоваться уже готовым решением в составе MulTEx — Высота/Ширина объединенной ячейки.

    Источник

    VBA Excel. Автоподбор ширины объединенной ячейки

    Автоподбор ширины объединенной ячейки с помощью кода VBA Excel, когда метод AutoFit не работает. Обработка ячеек по списку адресов из массива.

    Автоподбор ширины ячейки

    К сожалению, в объединенных ячейках метод VBA Excel AutoFit не работает. Но есть возможность подогнать ширину или высоту такой ячейки под длину текста с помощью макроса.

    Здесь мы рассмотрим макрос для автоподбора ширины ячейки, объединенной с другими по горизонтали в одной строке, которые обычно используются в заголовках электронных таблиц Excel. Ширина столбцов, пересекающихся с объединенной ячейкой, будет одинаковой. Код работает и с необъединенными ячейками.

    Для решения задачи по автоподбору ширины необходимо с помощью кода VBA определить:

    1. Длину текста (количество символов). Длина одного символа текста со шрифтом и его размером по умолчанию приблизительно соответствует длине символа, в котором измеряется ширина ячейки.
    2. Размер шрифта, чтобы рассчитать коэффициент, увеличивающий или уменьшающий ширину ячейки в зависимости от его (шрифта) размера.
    3. Количество столбцов в объединенной ячейке, чтобы вычислить ширину одного столбца.

    Макрос VBA Excel для автоподбора ширины ячейки с учетом размера используемого шрифта:

    • myCell — отдельная ячейка в объединенной;
    • myLen — длина текста в активной ячейке;
    • myCount — количество столбцов, которое соответствует количеству горизонтально расположенных отдельных ячеек в объединенной;
    • k — коэффициент, вносящий поправку в зависимости от размера шрифта;
    • n — размер шрифта по умолчанию.*

    * У меня по умолчанию установлен шрифт Calibri размером 11, поэтому n = 11. Если у вас по умолчанию Arial размером 10, тогда и в коде укажите n = 10. Далее подкорректируйте значение переменной n опытным путем, так как длина текста зависит от процентного соотношения широких и узких символов, если шрифт не моноширинный. Переменной n можно присваивать и дробные значения для более точного автоподбора.

    Данный код VBA Excel работает с выделенной ячейкой. Вы можете задать список адресов объединенных ячеек и пройтись макросом по каждой из них.

    Обработка списка ячеек

    Укажите список объединенных ячеек в качестве аргументов функции Array. Для списка используйте адреса только первых ячеек из состава объединенных. Можно добавлять в список и адреса одиночных ячеек.

    Источник

    Автоподбор ширины столбца excel vba

    Информация о сайте

    Инструменты и настройки

    Excel Windows
    и
    Excel Macintosh

    Вопросы и решения

    Работа и общение

    Работа форума и сайта

    Функции листа Excel

    = Мир MS Excel/Автоподбор ширины столбцов — Мир MS Excel

    Войти через uID

    Войти через uID

    Автоподбор ширины столбцов

    Pelena Дата: Пятница, 08.06.2012, 21:33 | Сообщение № 1
    «Черт возьми, Холмс! Но как. »
    Ю-money 41001765434816

    Ответить

    RAN Дата: Пятница, 08.06.2012, 22:14 | Сообщение № 2
    Быть или не быть, вот в чем загвоздка!

    Ответить

    Gustav Дата: Пятница, 08.06.2012, 22:28 | Сообщение № 3
    Pelena Дата: Пятница, 08.06.2012, 22:39 | Сообщение № 4
    «Черт возьми, Холмс! Но как. »
    Ю-money 41001765434816

    Ответить

    RAN Дата: Пятница, 08.06.2012, 22:48 | Сообщение № 5
    Быть или не быть, вот в чем загвоздка!

    Ответить

    Pelena Дата: Пятница, 08.06.2012, 22:54 | Сообщение № 6
    «Черт возьми, Холмс! Но как. »
    Ю-money 41001765434816

    Ответить

    Gustav Дата: Суббота, 09.06.2012, 00:19 | Сообщение № 7
    Pelena Дата: Суббота, 09.06.2012, 09:50 | Сообщение № 8

    Gustav, спасибо. То есть в контексте ширины столбца, в общем-то не важно, пишу я Range(«B2:K4»).Columns.AutoFit или Range(«B2:K4»).EntireColumn.AutoFit ?
    А вот мой вариант Sheets(1).Columns.AutoFit, наверное, не совсем удачный, так как идет обращение ко всем столбцам листа, а не только к заполненным. В этом плане использование Range(«A1»).CurrentRegion более оптимально. Я правильно понимаю?

    ЗЫ: извиняюсь за глупые вопросы, но с объектами Excel практически не знакома, а тупо копировать/вставить не привыкла

    Gustav, спасибо. То есть в контексте ширины столбца, в общем-то не важно, пишу я Range(«B2:K4»).Columns.AutoFit или Range(«B2:K4»).EntireColumn.AutoFit ?
    А вот мой вариант Sheets(1).Columns.AutoFit, наверное, не совсем удачный, так как идет обращение ко всем столбцам листа, а не только к заполненным. В этом плане использование Range(«A1»).CurrentRegion более оптимально. Я правильно понимаю?

    ЗЫ: извиняюсь за глупые вопросы, но с объектами Excel практически не знакома, а тупо копировать/вставить не привыкла Pelena

    «Черт возьми, Холмс! Но как. »
    Ю-money 41001765434816

    Ответить

    Сообщение Gustav, спасибо. То есть в контексте ширины столбца, в общем-то не важно, пишу я Range(«B2:K4»).Columns.AutoFit или Range(«B2:K4»).EntireColumn.AutoFit ?
    А вот мой вариант Sheets(1).Columns.AutoFit, наверное, не совсем удачный, так как идет обращение ко всем столбцам листа, а не только к заполненным. В этом плане использование Range(«A1»).CurrentRegion более оптимально. Я правильно понимаю?

    ЗЫ: извиняюсь за глупые вопросы, но с объектами Excel практически не знакома, а тупо копировать/вставить не привыкла Автор — Pelena
    Дата добавления — 09.06.2012 в 09:50

    Источник

    Adblock
    detector

    Понравилась статья? Поделить с друзьями:
  • Excel vba абсолютная ссылка в excel
  • Excel vba time from date
  • Excel vba xlsm xlsx
  • Excel vba time formats
  • Excel vba worksheetfunction trim