简体   繁体   English

Excel VBA 在1行代码中隐藏几列

[英]Excel VBA hide several columns in 1 line of code

I want to hide several columns (that's not close to each other) in 1 line (shown below) in VBA but it doesn't work.我想在 VBA 的 1 行(如下所示)中隐藏几列(彼此不接近),但它不起作用。 What's wrong with it?它出什么问题了?

Columns("A, C:D").hidden = True

Use Range.EntireColumn .使用Range.EntireColumn

Range("A:A,C:D").EntireColumn.Hidden = True

This thread is similar , and this answer demonstrates that Union is another option here as well. 这个线程是相似的,这个答案表明Union也是这里的另一个选择。

Note that .EntireColumn is necessary;请注意, .EntireColumn是必需的; omitting it will throw a省略它会抛出一个

Run-time error '1004':运行时错误“1004”:

Unable to set the Hidden property of the Range class.无法设置范围 class 的隐藏属性。

Hide Columns Using Union使用Union隐藏列

  • The best answer is already posted so here is kind of a cheating one: it is one line, but uses a function (with 'several' lines).最好的答案已经发布,所以这里有点作弊:它是一条线,但使用 function (带有“几条”线)。
Option Explicit

Sub hideColumns()
    CombinedColumns(ActiveSheet, "A,C,H,K:M,O,R:U").Hidden = True
End Sub

Function CombinedColumns( _
    ByVal ws As Worksheet, _
    ByVal ColumnsList As String, _
    Optional ByVal Delimiter As String = ",") _
As Range
    Dim Cols() As String: Cols = Split(ColumnsList, Delimiter)
    Dim rg As Range
    Dim n As Long
    For n = 0 To UBound(Cols)
        If rg Is Nothing Then
            Set rg = ws.Columns(Cols(n))
        Else
            Set rg = Union(rg, ws.Columns(Cols(n)))
        End If
    Next n
    If Not rg Is Nothing Then
        Set CombinedColumns = rg.EntireColumn
    End If
End Function

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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