簡體   English   中英

如果單元格包含文本,則VBA宏可以運行,但如果包含數字,則不能運行

[英]VBA Macro that works IF a cell contains text but not if it contains a number

嗨,我目前正在使用一個宏,該宏可以為我自動格式化表格並集中對齊所有單元格,但第一個選定列中的單元格除外。

我想知道是否有一種方法可以對此進行調整,以便第一個選定的列僅在包含文本而不是在包含數字的情況下才向左對齊

這是代碼:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM