簡體   English   中英

運行時錯誤“1004”:object“_Global”的方法“范圍”失敗問題(范圍(ActiveCell).Offset(-10, 1).Select)

[英]Run-time error '1004': Method 'Range' of object '_Global' failed problem with (Range(ActiveCell).Offset(-10, 1).Select)

我正在嘗試為 excel 創建一個 vba 代碼,如果 10 個漸進單元格的單元格為空,則在移動到下一列之前隱藏一列,從單元格 m9 開始。 但是,我無法解決此錯誤消息。 我是 VBA 的新手,所以我不確定如何繼續。 任何幫助將不勝感激。 謝謝你。

Sub HideColumns()
' Assumed if empty cell for 10 progressive cells in the same column, then is empty
' for the entirety of the test

' Our tests start at cell M9, so we will use a conditional loop to use the offset
' method on the range object from there
    StartCell = ActiveSheet.Range("M9").Select
    For i = 1 To 10
        If IsEmpty(ActiveCell.Value) = True Then
            Range(ActiveCell).Offset(i).Select
        ElseIf IsEmpty(ActiveCell.Value) = False Then
            Exit For
        End If
    Next i
    
    If i = 10 Then
            HiddenColoumn = ActiveCell.Column
            Columns("HiddenColoumn:HiddenColoumn").Select
            Selection.EntireColumn.Hidden = True ' now the column is hidden as there is no data for 10 progressive cells
            Range(ActiveCell).Offset(-10, 1).Select
            i = 1 ' reset counter for next loop
    ElseIf i <> 10 Then
            Range(ActiveCell).Offset(-10, 1).Select
            i = 1 ' reset counter for next loop
    End If
       

第一:不要 select 任何東西。 您只需指定其地址即可尋址任何單元格或范圍。 第二:任務不是檢查前10個單元格是否為空白,而是該列中是否有10個連續的空白單元格。 如果 M9:M10 和 M16 有值但所有其他單元格都是空白的怎么辦? 那么知道工作表中有多少行是很重要的,因為只看一列你無法知道這 10 個單元格是空白的(在工作表內)還是非空白的(在工作表下面)。

因此,您得出了不同的編碼策略。

Sub HideColumns()
    ' 257
    ' Assumed if empty cell for 10 progressive cells in the same column, then is empty
    ' for the entirety of the test
    
    Dim Blank           As Integer              ' count blank cells
    Dim Cl              As Long                 ' last used column in the sheet
    Dim Rl              As Long                 ' last used row in the sheet
    Dim C               As Long                 ' loop counter: columns
    Dim R               As Long                 ' loop counter: rows
    
    With Worksheets("Sheet1")                   ' better (meaning safer!) than 'ActiveSheet'
        With .UsedRange
            Cl = .Columns.Count + .Column - 1
            Rl = .Rows.Count + .Row - 1
        End With
        
        ' Our tests start at cell M9,
        For C = .Columns("M").Column To Cl
            Blank = 0
            For R = 9 To Rl
                If .Cells(R, C).Value = "" Then
                    Blank = Blank + 1
                    If Blank > 9 Then Exit For
                Else
                    Blank = 0
                End If
            Next R
            .Columns(C).Hidden = (Blank = 10)
        Next C
    End With
End Sub

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM