Home » excel » VBA Excel VerticalAlignment = xlCenter not working

VBA Excel VerticalAlignment = xlCenter not working

Posted by: admin March 9, 2020 Leave a comment

Questions:

The below code selects the sheet but fails to align the cells to center.

                wb.Sheets(1).Columns("A:L").Select
                With Selection
                    .VerticalAlignment = xlCenter
                End With

Thanks!

wb.Sheets(1).Activate
wb.Sheets(1).Columns("A:L").Select
With Selection
  .VerticalAlignment = xlCenter
End With 

Selects the entire sheet but it’s not changing the vertical alignment to center.

wb.Sheets(1).Columns("A:L").VerticalAlignment = xlCenter

Does nothing.

I don’t want HorizontalAlignment 🙂

I found out the column has VerticalAlignment set to xlCenter but the Cells underneath the column do not have VerticalAlignment set to xlCenter.

How to&Answers:

Don’t Select and don’t work with Selection without a reason. That’s Recorder’s stuff. It is longer to read, slower to execute, and prone to error.

wb.Sheets(1).Columns("A:L").VerticalAlignment = xlCenter is much better.

If you need to do several things with the same range, then use

with wb.Sheets(1).Columns("A:L")
      .VerticalAlignment = xlCenter
      .somethingElse
End with

Answer:

This is a common error for those newly learning the Excel object model. Every worksheet must have a current selected range, but Selection always points to the selected range on the active worksheet. You have to .Activate a sheet for the selected range on that sheet to be the Selection object.

wb.Sheets(1).Activate
wb.Sheets(1).Columns("A:L").Select
With Selection
  .VerticalAlignment = xlCenter
End With 

Or you could change your code to not rely on the Selection object:

wb.Sheets(1).Columns("A:L").VerticalAlignment = xlCenter

Answer:

Replace .VerticalAlignment = xlCenter with .HorizontalAlignment = xlCenter.