Wednesday, April 10, 2013

Select Columns From Another Sheet With VBA

Microsoft Excel

 

First Image
(Figure 1) Control Sheet with Command Button and Yes/No Criteria
Problem:

You want to use VBA (Visual Basic for Applications) in Microsoft Excel to hide columns in a different sheet than the one with the controls.

Solution:

This example works with Excel 2003 or 2007. It uses a workbook with three worksheets named Control, Labor, and Report. (See Figure 1)


The Control sheet has two criteria lines that let the user choose to hide or show a sheet named Labor. -OR- to hide or show three columns (C, D, and E) in a worksheet called Report.

The VBA Code to do this follows:
Second Image
(Figure 2) VBA Code to show and hide the sheets and columns
The first paragraph selects cell D2 ( Show Labor Sheet) and tests the value. If the user chose Yes, then the code shows how to show/unhide a worksheet. Else (the user chose No) the code shows how to hide a worksheet. These lines use the Sheets collection where the specific sheet name is specified. The same result could be obtained by using
Sheets(1).Visible = True

The Sheets collection is an array that includes all existing worksheets in each workbook. The specific sheet can be referenced by its number in the array (1) or its specific name (``Labor``).

The second paragraph shows the code to hide or show columns in a worksheet. Since we are doing this to columns in another worksheet, we must designate which sheet first

Sheets(``Report``)

then designate which columns to hide
.Columns(``C:E``)

Finally we specify that the entire column is to be hidden or shown

.EntireColumn.Hidden = True


The result is shown below:
Third Image
(Figure 3) Report Sheet with Columns C, D, and E Hidden - the Labor sheet is also hidden.

No comments: