如何在vba中找到最后一个可见列号?

时间:2016-04-15 01:00:45

标签: excel excel-vba vba

如何使用vba找到工作表中的最后一个可见列(未隐藏)?

我使用了以下代码:

Dim LastColumn As Integer
If WorksheetFunction.CountA(Cells) > 0 Then
            'Search for any entry, by searching backwards by Columns.

LastColumn = Cells.Find(What:="*", After:=[A1], SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column

MsgBox LastColumn
End If

但它给了我最后一列号。我想要最后一个可见的列号。 有什么帮助吗?

3 个答案:

答案 0 :(得分:2)

尝试以下方法。您可以使用xlCellTypeVisible指定隐藏和非隐藏单元格。

Sub counthidden()
MsgBox ActiveSheet.UsedRange.SpecialCells(xlCellTypeVisible).Columns.Count
End Sub

答案 1 :(得分:2)

您可以使用SpecialCells来提供帮助:

Dim rng1 As Range
Dim rng2 As Range

On Error Resume Next
Set rng1 = ActiveSheet.UsedRange.SpecialCells(xlVisible)
On Error GoTo 0

If Not rng1 Is Nothing Then
    Set rng2 = rng1.Find(What:="*", After:=rng1.Cells(1), SearchOrder:=xlByColumns, SearchDirection:=xlPrevious)
    MsgBox rng2.Column
End If

答案 2 :(得分:0)

结果令人惊讶的简单。我一直在寻找类似的问题。

Sub lastVisibleColumn()
' This should select the last fully visible column on the active window

' This part selects the current top left visible cell regardless of zoom
    ActiveWindow.VisibleRange.Select
    ActiveCell.Offset(0, 0).Select
    startColumn = ActiveCell.Column

' Large scroll right 1 page
    ActiveWindow.LargeScroll ToRight:=1
    ActiveWindow.VisibleRange.Select

' Select the top left cell again, -1 column to get to
'the previous scrollable page
    ActiveCell.Offset(0, -1).Select
    ActiveWindow.LargeScroll ToLeft:=1
    lastColumn = ActiveCell.Column
End Sub