VBA宏,如果单元格包含文本,则无效,但如果它包含数字则不工作



嗨,我目前正在使用一个宏,该宏可以为我自动格式化表格并集中对齐除第一选定列中的单元格之外的所有单元格。

我想知道是否有办法调整它,以便仅当包含文本而不是包含数字时,第一个选定的列才会左对齐

代码如下:

Sub Test_align_left()
With Selection
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlCenter
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
Selection.Columns(1).Select
On Error Resume Next
With Selection
.SpecialCells(xlCellTypeConstants, xlTextValues).HorizontalAlignment = xlLeft
.SpecialCells(xlCellTypeFormulas, xlTextValues).HorizontalAlignment = xlLeft
End With
End Sub

提前感谢,

托马斯

如果您的意思是文本左对齐或数字居中,那么这里有一种方法可以避免循环遍历每个单元格。

Sub x()
On Error Resume Next
With Columns(1)
.SpecialCells(xlCellTypeConstants, xlTextValues).HorizontalAlignment = xlLeft
.SpecialCells(xlCellTypeConstants, xlNumbers).HorizontalAlignment = xlCenter
.SpecialCells(xlCellTypeFormulas, xlNumbers).HorizontalAlignment = xlCenter
.SpecialCells(xlCellTypeFormulas, xlTextValues).HorizontalAlignment = xlLeft
End With
End Sub

如果您只想保留第一列,您可以执行以下操作:

Sub Test_align_left()
'Test_align_left Macro
With Selection.offset(0,1).resize(,Selection.columns.count-1)
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlCenter
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
End Sub

相关内容

最新更新