How to determine if there are hidden columns when copying in Excel VBA

本秂侑毒 提交于 2019-12-24 10:48:09

问题


As the title explains, I have an Excel 2003 workbook and I'm copying a number of columns of one sheet to another in VBA. Unknown to me, someone has hidden a few columns on the source sheet and it has messed up how I process the cells in the destination sheet.

How can I programmically determine:

  1. IF there are hidden columns
  2. WHICH columns are hidden?

Thanks! JFV


回答1:


For a Range, check the Range.Hidden property.

The following snippet from MSDN is a good example of how to hide/unhide a row/column:

 Worksheets("Sheet1").Columns("C").Hidden = True

You can also test the value with an If statement:

 For ColCounter = 1 To 10
      If Columns("C").Hidden = True Then
           Columns("C").Hidden = False
      End If
 Next



回答2:


If you only want to copy the visible files then one option that is quite nice it to select only the visible columns as a range.

This can be done by

Set visrng =rng.SpecialCells(xlCellTypeVisible)

It wasn't clear to me if this would be useful in your case, but I decided to post it as it could be useful to others.




回答3:


Copying Visible Cells to another Range and then comparing the number of cells in each is probably the easiest way to determine if there are Hidden Cells in the Range

eg

Selection.SpecialCells(xlCellTypeVisible).Copy Destination:=VisRan

If Not Selection.Cells.Count = VisRan.Cells.Count Then
    MsgBox "Selection contains Hidden Cells"
End If



回答4:


You can check by using a function like:

Function IsColumnHidden(column As Variant) as Boolean
    IsColumnHidden = False
    If Columns(column).ColumnWidth = 0.0 Then IsColumnHidden = True
End Function

A Column width or Row height of 0.0 is an indicator of whether or not the range is hidden.




回答5:


Here is one that I have tested and it works well if you want to hide/unhide columns

Sub Macro1_Test_Hidden() ' ' Macro1_Test_Hidden Macro ' ' ' If Columns("BH:XFA").Hidden = False Then Columns("BH:XFA").Select Range("BH:XFA").Activate Selection.EntireColumn.Hidden = True Else Columns("BH:XFA").Select Range("BH:XFA").Activate Selection.EntireColumn.Hidden = False End If ' ' End Sub



来源:https://stackoverflow.com/questions/1088523/how-to-determine-if-there-are-hidden-columns-when-copying-in-excel-vba

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!