DEV Community

Andrews
Andrews

Posted on • Originally published at geekexcel.com on

Autofit Columns using Macros (VBA) in Excel Office 365!!

Autofit Columns using Macros (VBA) in Excel:

In this guide, you will understand the steps to Autofit Columns using Macros in Excel Office 365 with an example. Let’s get into this article!! Get an official version of MS Excel from the following link: https://www.microsoft.com/en-in/microsoft-365/excel

Steps to Autofit Columns using Macros:

To autofit columns in an Excel spreadsheet using Macros, follow the below steps.

  • In the below example, you can see the columns that are not in the proper order. So we are going to autofit columns using the VBA & Macros.

Example data
Example data

  • Go to the Developer Tab, choose the Visual Basic option in the Code section.

Choose Visual Basic option
Choose Visual Basic option

  • You need to activate the sheet where you want to autofit the rows.
  • Now, enter the below code.

VBA code for autofit columns

Sub AutoFitAllColumns()

Activate Cells.Select

‘Use this code to get the result!

Cells.EntireColumn.AutoFit

End Sub

  • You need to save the code by selecting it. Then close the window.

Enter the Source Code
Enter the Source Code

  • Then, open the sheet that contains the data, and on the Developer Tab, ** choose the Macros option in the Code** section.

Choose the Macros option
Choose the Macros option

  • You have to make sure that your Macro is selected and click the Run button.

Macro dialog box
Macro dialog box

  • Now, all the columns are automatically fitted in the Excel spreadsheet.

Before running the VBA & Macros Code:

Example data
Example data

After running the VBA & Macros Code:

  • Result

Result

Wrap-Up:

In this guide, we helped you to learn the steps to Autofit Columns using Macros in Excel Office 365 with an example. Kindly, share your feedback in the below comment section. Thanks for visiting Geek Excel. Keep Learning!!

Top comments (0)