VBA筛选后获取首个可见行报错求助(原代码曾正常运行)
VBA筛选后获取可见行号报错排查问题
原本运行正常的VBA代码,用于筛选数据区域后获取首个可见行的行号,对比currentregion、SpecialCells等方法后选择SpecialCells实现。
仅将wsa变量提前声明后,对同一数据源执行两次筛选操作时,原本正常的语句:
a = wsf.AutoFilter.Range.Offset(1, 0).SpecialCells(xlCellTypeVisible)(1).Row
开始抛出错误1004 - 应用程序或对象定义的错误。相关数据源及wsf的定义均未改变,理论上变量声明位置调整不应产生影响。
多方排查无果,尝试其他方法后虽不再报错,但返回的行号始终为1(测试预期应为48000左右),而下方功能完全相同的wsa相关语句却运行正常。两个文件均为xlsm格式,工作表设置与筛选操作均无误,恳请协助排查。
相关代码
Dim deb As Date: deb = Now() Dim owa As Workbook: Set owa = ThisWorkbook Dim ows As Worksheet: Set ows = owa.Worksheets("Feuil1") Dim PremAg As Range: Set PremAg = ows.Range("w2") Dim LastAg As Range: Set LastAg = ows.Range("w" & ows.Cells(Rows.Count, "w").End(xlUp).Row) Dim RngAg As Range: Set RngAg = ows.Range(PremAg, LastAg) 'full list of criterias I'll apply Dim CellClient As Range Dim CellFact As Range Dim Agence As String Dim wba As Workbook 'file with clients' info Dim wsa As Worksheet 'relevant sheet Dim RngClient As Range 'full list of clients' IDs according to client file Dim RngFact As Range 'same but for invoices file Dim Poubelle As Range 'Trash that stocks used up invoices to then delete them once I used them Dim n As Integer n = 0 Dim wbf As Workbook 'invoices file Dim wsf As Worksheet 'relevant sheet for invoices Dim a As Integer Dim b As Integer Dim c As Integer Dim d As Integer Set wbf = Workbooks.Open("C:\Users\QNS691\OneDrive\Documents\Excel\par agence 5\facts torturées2.xlsm") Set wsf = wbf.Worksheets(1) Set wba = Workbooks.Open("C:\Users\QNS691\OneDrive\Documents\Excel\par agence 5\full.xlsm") Set wsa = wba.Worksheets(1) Application.DisplayAlerts = False For Each CellAg In RngAg wsf.Range("A1").AutoFilter field:=7, Criteria1:=CStr(CellAg) 'filter works well a = wsf.AutoFilter.Range.Offset(1, 0).SpecialCells(xlCellTypeVisible)(1).Row 'and then there's this little thing that worked just fine but then threw a fit b = wsf.Range("g1").End(xlDown).Row wsa.Range("A1").AutoFilter field:=7, Criteria1:=CellAg c = wsa.AutoFilter.Range.Offset(1, 0).SpecialCells(xlCellTypeVisible)(1).Row 'while that one works ok... d = wsa.Range("g1").End(xlDown).Row Set RngFact = wsf.Range("g" & a, "g" & b) Set RngClient = wsa.Range("g" & c, "g" & d) For Each CellClient In RngClient n = 0 ag = wsa.Cells(CellClient.Row, 7) For Each CellFact In RngFact If CellClient = CellFact And ag = wsf.Cells(CellFact.Row, 7) Then n = n + 1 If Poubelle Is Nothing Then Set Poubelle = CellFact Else Set Poubelle = Union(Poubelle, CellFact) End If End If Next CellFact If Not Poubelle Is Nothing Then 'Debug.Print Poubelle.Address Poubelle.EntireRow.Delete End If Set Poubelle = Nothing If n > 1 Then wsa.Cells(CellClient.Row, 9) = n End If Next CellClient wba.Save wbf.Save Next CellAg Application.DisplayAlerts = True MsgBox y & Chr(10) & deb & " " & Now() End Sub
内容的提问来源于stack exchange,提问作者ThismaddePro
相关产品推荐
相关产品推荐

