VBA Excel VerticalAlignment = xlCenter 不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7432259/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 11:53:20  来源:igfitidea点击:

VBA Excel VerticalAlignment = xlCenter not working

excelvba

提问by Bruno

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 :)

我不想要 Horizo​​ntalAlignment :)

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

我发现该列已将 VerticalAlignment 设置为 xlCenter,但该列下方的单元格没有将 VerticalAlignment 设置为 xlCenter。

回答by Patrick Honorez

Don't Selectand don't work with Selectionwithout a reason. That's Recorder's stuff. It is longer to read, slower to execute, and prone to error.

不要Select和不要Selection无缘无故地工作。那是录音机的东西。读取时间较长,执行速度较慢,并且容易出错。

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

wb.Sheets(1).Columns("A:L").VerticalAlignment = xlCenter好多了。

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

回答by adamleerich

This is a common error for those newly learning the Excel object model. Every worksheet must have a current selected range, but Selectionalways points to the selected range on the activeworksheet. You have to .Activatea sheet for the selected range on that sheet to be the Selectionobject.

对于刚开始学习 Excel 对象模型的人来说,这是一个常见的错误。每个工作表都必须有一个当前选定的范围,但Selection始终指向活动工作表上的选定范围。您必须.Activate将该工作表上选定范围的工作表作为Selection对象。

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 Selectionobject:

或者您可以更改代码以不依赖Selection对象:

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

回答by Joel

Replace .VerticalAlignment = xlCenterwith .HorizontalAlignment = xlCenter.

替换.VerticalAlignment = xlCenter.HorizontalAlignment = xlCenter