简体   繁体   中英

How to hide multiple columns in Excel sheet?

I'm using 4 sequential columns from sheet 1 to generate charts in sheet 2. I want to hide those 4 columns in sheet 1.

I've tried the below code to hide the columns:

Set allColumns = dataSheet.Columns("J:M")
allColumns.Hidden = True

Constants and References

Sub AllCol()

  Const cVntSheet As Variant = "Sheet1"   ' Worksheet Name/Index
  Const cStrRange As String = "J:M"       ' Range Address

  Dim dataSheet As Worksheet              ' Worksheet

  ' Create a reference to the worksheet.
  Set dataSheet = Worksheets(cVntSheet)

  ' Hide the range.
  dataSheet.Columns(cStrRange).Hidden = True

End Sub

Swap Sheet1 with your actual sheet name.

Sub HideMe()

    ThisWorkbook.Sheets("Sheet1").Columns("J:M").Hidden = True

End Sub

Notice this can be done in one line. If you want to use variables (workbook or worksheets), they should build the above string when combined

Something like:

Dim wb as Workbook: Set wb = ThisWorkbook
Dim ws as Worksheet: Set ws = wb.Sheets("Sheet1")
Dim hm as String: hm = "J:M"

ws.Columns(hm).Hidden = True

If you substitute your variables into the last line, you will end up with the exact same line of code shown in the first 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