excel UsedRange.Offset给出的运行时错误为

eimct9ow  于 2023-10-22  发布在  其他
关注(0)|答案(2)|浏览(98)

我有一个工作表,我试图过滤数据,然后想将过滤后的行粘贴到另一个工作簿。
下面的代码

MySheet.UsedRange.Offset(1, 0).Resize(MySheet.UsedRange.Rows.Count - 1).SpecialCells(xlCellTypeVisible).Copy

运行时错误'1004':应用程序定义的或对象定义的错误”,但令人惊讶的是,当我尝试逐行调试时,相同的代码工作得很好。
无法理解直接运行上述代码的debug v/s之间的区别。
任何指示都会有帮助。
谢谢

1zmg4dgp

1zmg4dgp1#

底部空白时复制过滤数据

Sub AutoFilterCopyBottomBlanks()
    
    Const TURN_OFF_AUTOFILTER As Boolean = True
    
    Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
    Dim MySheet As Worksheet: Set MySheet = wb.Sheets("Sheet1")
    
    ' Reference the table range ('trg')
    ' excluding any consecutive bottom-most rows that are blank.
    
    Dim trg As Range, drCount As Long
    
    With MySheet
        ' Turn off auto filtering (for the 'Find' method to work correctly).
        ' Also, make sure there are no hidden rows because the 'Find' method
        ' due to 'xlValues' will fail if any consecutive bottom-most rows
        ' are hidden.
        If .AutoFilterMode Then .AutoFilterMode = False
        ' Note that '.ShowAllData' is unsafe since the auto filter could
        ' be applied to only a portion of the range.
        With .UsedRange
            Dim lcell As Range:
            Set lcell = .Find("*", , xlValues, , xlByRows, xlPrevious)
            If lcell Is Nothing Then Exit Sub ' the worksheet is blank
            drCount = lcell.Row - .Row ' data rows (header row excluded)
            If drCount = 0 Then Exit Sub ' only a single row (headers!?)
            Set trg = .Resize(drCount + 1)
        End With
    End With
    
    ' Apply the filter (modify as required).
    trg.AutoFilter 1, "Criteria" '
        
    ' Attempt to reference the filtered rows ('vrg' - visible range).
    Dim vrg As Range:
    On Error Resume Next ' prevent error if no cells found
        Set vrg = trg.Resize(drCount).Offset(1).SpecialCells(xlCellTypeVisible)
    On Error GoTo 0
    
    ' Turn off auto filtering. It is optional in case of copying.
    ' It is a necessary step to not to have to delete
    ' entire rows when deleting the filtered rows.
    If TURN_OFF_AUTOFILTER Then
        MySheet.AutoFilterMode = False
    End If
    
    If vrg Is Nothing Then Exit Sub ' no filtered rows
    
    ' Continue with the copy code...
    vrg.Copy

End Sub
7cwmlq89

7cwmlq892#

如果没有可见的数据(所有数据行都被隐藏),OP的代码将引发1004。
试试看吧

Sub Demo()
    Dim c As Range, mysheet As Worksheet
    Set mysheet = ActiveSheet
    On Error Resume Next
    Set c = mysheet.UsedRange.Offset(1, 0).Resize(mysheet.UsedRange.Rows.Count - 1).SpecialCells(xlCellTypeVisible)
    On Error GoTo 0
    If Not c Is Nothing Then
        c.Copy
    Else
        MsgBox "No data"
    End If
End Sub
  • Microsoft文档:*

Range.SpecialCells method (Excel)

相关问题