简体   繁体   中英

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

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:

Pic1 - 这是我开始的示例表

I select the first two rows:

Pic2 - 我选择前两行

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:

Pic3 - 它工作得很好,第一行在第一列中包含一个数字,因此它居中对齐,第二行在第一列中有文本,因此它向左对齐 - 到目前为止一切顺利

But, if I run the macro on this row:

Pic4 - 但是,如果我在这一行运行宏:

Suddenly all cells with text align to the left, regardless of whether I selected them or not:

Pic5 - 突然所有带有文本的单元格都向左对齐,无论我是否选择它们

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM