用于选择动态范围中第一个可见列的VBA代码

时间:2015-07-14 16:18:13

标签: excel-vba vba excel

我无法找到此查询的确切答案。我需要代码来访问范围中的第一个未隐藏列。动态隐藏或取消隐藏列,每次代码必须选择未隐藏范围内的第一列。有什么想法?

我目前的尝试:

Private Sub Test1_Click() 
    Application.EnableCancelKey = xlDisabled 
    On Error Resume Next 
    Dim answer As String 
    'ActiveSheet.Unprotect "" 
    Dim rw As Range 
    For Each rw In Sheet1.Range("$c$30:$e$39") 
        If Sheet1.Range("b27").Text <> "" Or Sheet1.Range("b30:b39").Text <> "" Then
            rw.Formula = rw.Offset(0, -1).Value * Sheet1.Range("b27").Value + rw.Offset(0, -1).Value 
        Else 
            answer = MsgBox("Eh!!! There is no data to copy..Please fill the first column and try again", vbOKOnly, "Alert") 
            Exit Sub 
        End If 
        Next rw 
    'ActiveSheet.Protect "" 
End Sub

1 个答案:

答案 0 :(得分:0)

给定任意范围,如:

范围(&#34; C3:H13&#34)

我们希望选择该范围内的第一个非隐藏列:

Sub SelectFirstVisibleColumn()
    Dim r As Range
    Set r = Range("C3:H13")
    nLastRow = r.Rows.Count + r.Row - 1
    nLastColumn = r.Columns.Count + r.Column - 1
    nFirstRow = r.Row
    nFirstColumn = r.Column

    For i = nFirstColumn To nLastColumn
        If Cells(1, i).EntireColumn.Hidden = False Then
            Cells(1, i).EntireColumn.Select
            Exit Sub
        End If
    Next i
End Sub

如果我们想将选择限制在该范围内的单元格而不是整个列,那么:

Sub SelectFirstVisibleColumn()
    Dim r As Range
    Set r = Range("C3:H13")
    nLastRow = r.Rows.Count + r.Row - 1
    nLastColumn = r.Columns.Count + r.Column - 1
    nFirstRow = r.Row
    nFirstColumn = r.Column

    For i = nFirstColumn To nLastColumn
        If Cells(1, i).EntireColumn.Hidden = False Then
            Intersect(r, Cells(1, i).EntireColumn).Select
            Exit Sub
        End If
    Next i
End Sub

例如:

enter image description here