简体   繁体   中英

How do I select multiple column ranges using “If Columns” in VBA?

I'm using this code on a toggle button to hide/show columns in my spreadsheet.

Sub Button22_Click()
If Columns("D:E").Hidden = True Then
Columns("D:E").Hidden = False
Else
Columns("D:E").Hidden = True
End If
End Sub

This formula works great for columns D:E . The question is, how do I add other columns, both single and ranges, to this formula? Suppose I need to show/hide F:K and N as well, with the same button? I've tried things like ("D:E","F:K") and I get a runtime error. Any help is VERY appreciated.

Just syntax to hide a disjoint set of columns:

Sub dural()
   Range("D:E,L:L").EntireColumn.Hidden = True
End Sub

This will hide columns D, E, and L .

You have to use the Range object.

Range("D:E,F:K,N:N").Select
Selection.Hidden = True

https://msdn.microsoft.com/en-us/library/office/ff838238.aspx

Update:

Your code should look like this:

Sub Button22_Click()
    Range("D:E,F:K,N:N").Select
    Selection.EntireColumn.Hidden = Not Selection.EntireColumn.Hidden
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