在VBA中捕获“数据范围太复杂”错误

时间:2013-04-04 21:22:56

标签: excel vba excel-vba excel-2007

在excel宏中我正在努力将过滤后的数据复制到新工作表中以删除隐藏的行。这允许我对用户已过滤的数据运行更复杂的公式。对于复杂过滤的大型数据集,复制操作不再仅使用过滤数据,而是复制所有数据。

当我手动复制过程时,当我尝试复制过滤后的数据时,Excel给出了“数据范围太复杂”的错误。这很容易通过排序然后过滤来过去,但我无法弄清楚如何在VBA中捕获此错误。我想知道复制操作是否正常工作(并允许宏继续)或者选择是否过于复杂(并停止宏并提醒用户先尝试排序)。

知道我怎么能这样做吗?任何帮助将不胜感激。

以下相关代码:

    Select Case Range("GDT_Filtered").Value
    Case "Filtered Data"
        Worksheets.Add after:=Worksheets(Worksheets.Count)
        Set wRaw = ActiveSheet
        Sheets("Raw Data").Select
        lastRow = Range("A1").End(xlDown).Row
        Range("A1:S" & lastRow).Copy Destination:=wRaw.Range("A1")

    Case "All Data"
        Set wRaw = Sheets("Raw Data")
        On Error Resume Next
        wRaw.ShowAllData
        On Error GoTo 0
    End Select

谢谢!

萨姆

2 个答案:

答案 0 :(得分:1)

好吧,我已经找到了一个可管理的解决方案。

假设原始数据存储在工作表中,并且已过滤的数据被复制到工作表wTwo,以下代码将通过检查过滤和每个工作表中的行数来查找错误:

' Excel can't copy too many discontinuous sections. If it happens it won't throw
' an error but will copy ALL data instead of just filtered data. This checks that
' such an error has not occurred.
If wOne.AutoFilter.FilterMode = True Then
    If wOne.range("A1").End(xlDown).Row = wTwo.Range("A1").End(xlDown).Row Then
        MsgBox "Filtering has produced too many discontinuous selections. " & _ 
                "Try removing the filters, sorting data by the variables " & _ 
                "you wish to filter with, reapplying the filters, and " & _
                "trying again. Good luck!"
        GoTo 1
    End If
End If

答案 1 :(得分:0)

使用OnError

sub 

   On Error Goto 1

   do the copy, if it fails, code will jump to 1.

   On Error Goto 0 'zero means you are not doing any treatment for further errors

   continue the code

   exit sub 'you don't want the code to do error treatment below if there's no error

   1 Do what you need if error occurs

end sub