开发者

How to align cells to center?

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

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 vert开发者_如何学编程ical alignment to center.

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

I don't want HorizontalAlignment.

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


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

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


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


Replace .VerticalAlignment = xlCenter with .HorizontalAlignment = xlCenter.


Thanks it worked perfect

With Hoja.Range("A1:O1")
    .HorizontalAlignment = xlCenter
    .VerticalAlignment = xlBottom
    .WrapText = False
    .Orientation = 0
    .AddIndent = False
    .IndentLevel = 0
    .ShrinkToFit = False
    .ReadingOrder = xlContext
    .MergeCells = False
    .Font.Bold = True
    .Font.Size = 12
    .Interior.Color = RGB(255, 208, 0)
    .Font.Color = RGB(26, 20, 70)
End With
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜