【问题标题】:How can the vertical alignment of a range be changed without impacting the indent?如何在不影响缩进的情况下更改范围的垂直对齐方式?
【发布时间】:2018-09-05 00:00:46
【问题描述】:

在 Excel 中,将范围的垂直对齐方式从默认的 xlBottom 更改为 xlCenter 时,无论是使用普通用户界面还是使用 VBA,如下所示:

Range.VerticalAlignment = xlCenter

Excel 有时会删除这些单元格中文本的缩进设置。当目标范围同时包含缩进和未缩进的单元格时,似乎会发生这种情况。

使用 VBA,我如何设置 any 范围的垂直对齐方式并为该范围内的每个单元格保留单元格缩进?

【问题讨论】:

    标签: vba excel


    【解决方案1】:

    您可以使用RangeIndentLevel 属性:

    Sub Test()
        Dim rng As Range, r As Range
        Dim indent As Long
    
        Set rng = Sheet1.Range("A1:A10")
    
        For Each r In rng
            indent = r.IndentLevel
            r.VerticalAlignment = xlCenter
            r.IndentLevel = indent
        Next
    End Sub
    

    更新

    Chris Neilson pointed out 一样,当您遍历单元格时,单独更改对齐方式不会影响您的缩进,而rng.VerticalAlignment = xlCenter 会删除整个范围内的缩进。

    因此,这是迄今为止测试过的最快的方法(我的笔记本电脑上的运行时间为 0.41 秒):

    Sub Test()
        Application.ScreenUpdating = False
    
        Dim t As Variant: t = Timer
        Dim rng As Range, r As Range
    
        Set rng = Sheet1.Range("A1:A10000")
    
        For Each r In rng
            r.VerticalAlignment = xlCenter
        Next
    
        Debug.Print Timer - t
        Application.ScreenUpdating = True
    End Sub
    

    【讨论】:

    • 这只有在 (1) 范围内的所有单元格具有相同的缩进级别,并且 (2) 我事先知道缩进级别时才有效。我正在寻找一个通用的解决方案。
    • 你是对的。我第一次没有阅读您的警告。
    • @ChrisB,已更新(并删除了警告,现在已过时的 cmets)
    • 给了这个 +1。我在脚本执行期间关闭了屏幕更新,它将格式化 10,000 个单元格的时间从 8 秒减少到 2 秒。除非有人发布更有效(即更快)的方法,否则我会将其标记为答案。
    • @Chrisb 因为您一次循环并设置一个单元格的对齐方式,您可能也不需要设置缩进。删除它会加快一点
    猜你喜欢
    • 1970-01-01
    • 2019-06-29
    • 1970-01-01
    • 2012-02-06
    • 2021-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多