[英]VBA SpecialCells Macro bug
I'm currently using the following code to automatically align numbers, formulas and text in a table row centrally except for the first column in the selection which aligns left if it's text and centrally if it's not.我目前正在使用以下代码自动居中对齐表格行中的数字、公式和文本,除了选择中的第一列,如果它是文本,则向左对齐,如果不是,则居中对齐。
Annoyingly, however, if I only select one row, the macro starts running for every cell above and beneath the selection.然而,令人讨厌的是,如果我只选择一行,宏就会开始为所选内容上方和下方的每个单元格运行。 Is there a way to fix this?
有没有办法来解决这个问题?
Also, currently once the macro has finished running it ends on the first column of the selection.此外,目前一旦宏完成运行,它就会在选择的第一列结束。 Is there a way to make it end with the selection I started with (ie if I've selected cells A1:D1, once it's done running the currently selected cell will be A1 but I'd like it to still be highlighting A1:D1).
有没有办法让它以我开始的选择结束(即,如果我选择了单元格 A1:D1,一旦运行完毕,当前选定的单元格将是 A1,但我希望它仍然突出显示 A1:D1 )。
Apologies if anything is unclear如果有任何不清楚的地方,请见谅
Sub Test_align_left()
With Selection
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlCenter
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
This is an example table I start with:这是我开始的示例表:
I select the first two rows:我选择前两行:
And it works perfectly, the first row contains a number in the first column so it aligns centrally, and the second row has text in the first column so it aligns to the left - so far so good:它工作得很好,第一行在第一列中包含一个数字,因此它居中对齐,第二行在第一列中有文本,因此它向左对齐 - 到目前为止一切顺利:
But, if I run the macro on this row:但是,如果我在这一行运行宏:
Suddenly all cells with text align to the left, regardless of whether I selected them or not:突然所有带有文本的单元格都向左对齐,无论我是否选择了它们:
Something like this to handle the special case of one row:像这样处理一行的特殊情况:
Sub Test_align_left()
With Selection
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlCenter
With .Columns(1)
If .Cells.Count > 1 Then
On Error Resume Next
.SpecialCells(xlCellTypeConstants, xlTextValues).HorizontalAlignment = xlLeft
.SpecialCells(xlCellTypeFormulas, xlTextValues).HorizontalAlignment = xlLeft
Else
If Not IsNumeric(.Value) Then .HorizontalAlignment = xlLeft
End If
End With
End With
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.