vba 在 Excel 中左右对齐文本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45153155/
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 10:52:43  来源:igfitidea点击:

Align text to left and right in Excel?

excelvba

提问by Kevin López

I have a workbook in which I need to align text (from cells) to the left and the to the right. I have this so far but I don't know how to proceed.

我有一个工作簿,我需要在其中将文本(来自单元格)与左侧和右侧对齐。到目前为止,我有这个,但我不知道如何继续。

Sub M()

ActiveSheet.PageSetup.CenterHeader = ActiveSheet.Range("A1") & " " & 
ActiveSheet.Range("B1")

End Sub

I want to know in general how to override the alignment for text in each part of the header but in this instance, I need to have text aligned to the left in both the right and left headers.

我想知道一般如何覆盖标题每个部分中文本的对齐方式,但在这种情况下,我需要将左右标题中的文本都对齐到左侧。

采纳答案by YowE3K

I am interpreting your question as "I want to have one cell's value as the left part of my header, and another cell's value as the right part of my header".

我将您的问题解释为“我希望将一个单元格的值作为标题的左侧部分,将另一个单元格的值作为标题的右侧部分”。

If so, you probably want:

如果是这样,您可能想要:

Sub M()
    With ActiveSheet.PageSetup
        .LeftHeader = ActiveSheet.Range("A1").Value
        .CenterHeader = ""
        .RightHeader = ActiveSheet.Range("B1").Value
    End With
End Sub

回答by Jsleshem

To do this in Excel, select the section of cells needed to align. Then, type alt+H+A+Lfor left, alt+H+A+Cfor center, and alt+H+A+Rfor right.

要在 Excel 中执行此操作,请选择需要对齐的单元格部分。然后,型alt+ H+ A+L左,alt+ H+ A+C为中心,和alt+ H+ A+R右。

However, based on your question it seems like you want to do this in VBA instead of Excel. If that is the case, do this instead:

但是,根据您的问题,您似乎想在 VBA 而不是 Excel 中执行此操作。如果是这种情况,请改为执行以下操作:

Range(myRange).HorizontalAlignment = xlRightfor right, and Range(myRange).HorizontalAlignment = xlLeftfor left, where myRange is the range of cells.

Range(myRange).HorizontalAlignment = xlRight对于右侧和 Range(myRange).HorizontalAlignment = xlLeft左侧,其中 myRange 是单元格的范围。

回答by Zachary Summers

The HorizontalAlignment property of the Range should be what you're looking for. xlLeft or xlRight are values to align left or right.

Range 的 Horizo​​ntalAlignment 属性应该是您要查找的内容。xlLeft 或 xlRight 是左对齐或右对齐的值。

Range.HorizontalAlignment = xlLeft 

or

或者

Range.HorizontalAlignment = xlRight

E.G.

例如

Sub M()

ActiveSheet.PageSetup.CenterHeader = ActiveSheet.Range("A1") & " " & 
ActiveSheet.Range("B1").HorizontalAlignment = xlRight

End Sub

would align the B1 cell to the right.

将 B1 单元格向右对齐。

回答by BruceWayne

You can use Range("A1").HorizontalAlignment = xlLeftor ... = xlRight

您可以使用Range("A1").HorizontalAlignment = xlLeft... = xlRight

Of course, adjust the range(s) as necessary.

当然,根据需要调整范围。