在 Excel 2010 中使用 VBA 隐藏列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15048191/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Hide columns using VBA in Excel 2010
提问by user2103670
Based on the value stored in a specific cell such as A1
of a worksheet I would like to hide a number of columns in the worksheet starting with column B.
根据存储在特定单元格(例如A1
工作表)中的值,我想隐藏工作表中以 B 列开头的许多列。
Examples of what I am trying to do:
我正在尝试做的示例:
- If the value of cell A1 = 10, then hide column B plus 10 columns after B
- If the value of cell A2 = 11, then hide column B plus 11 columns after B
- 如果单元格 A1 的值 = 10,则隐藏 B 列加上 B 后的 10 列
- 如果单元格 A2 的值 = 11,则隐藏 B 列加上 B 后的 11 列
The difficulty is actually the way Excel (or least my Excel files) uses the alphabet (A, B, ...) for the name of the columns. I have done this on rows before using code like rows("2:" & range("A1").value)
and set .hide = true
困难实际上是 Excel(或至少我的 Excel 文件)使用字母表(A、B、...)作为列名的方式。在使用类似rows("2:" & range("A1").value)
和设置的代码之前,我已经对行进行了此操作.hide = true
采纳答案by Glenn Stevens
You can reference columns by their index number as such: Columns(indexnumber)
and you can use Resize()
to set the number of columns you want to select like so:
您可以通过它们的索引号来引用列:Columns(indexnumber)
并且您可以使用Resize()
来设置要选择的列数,如下所示:
Sub HideColumns()
Dim numColumnsToHide
numColumnsToHide = Cells(1, 1).Value
Columns(2).Resize(, numColumnsToHide).Select
Selection.EntireColumn.Hidden = True
End Sub
Obviously, this code doesn't have any validation of value in A1
so if someone runs HideColumns()
without an integer in A1
, bad things are going to happen. This also doesn't unhide any hidden columns.
显然,这段代码没有对 in 的值进行任何验证,A1
因此如果有人在HideColumns()
没有整数 in 的情况下运行A1
,就会发生不好的事情。这也不会取消隐藏任何隐藏的列。
回答by Excel Developers
I wanted to add a comment to Glenn's answer above but don't have enough reputation. What I was going to add was that you don't need to activate a sheet or select the columns, you can simply go ahead and hide the columns:
我想对上面格伦的回答添加评论,但没有足够的声誉。我要补充的是,您无需激活工作表或选择列,您只需继续隐藏列即可:
Worksheets("TheSheet").Columns(2).Resize(, numColumnsToHide).EntireColumn.Hidden = True