简体   繁体   English

Excel VBA-多次交互后停止在过滤器上选择可见行

[英]Excel VBA - Stops Selecting Visible Rows on Filter after many interations

My code takes a file name from TextBox1, opens that file and indexes through all the unique values in column B. It then takes a second file, file name in TextBox2, and filters it based on the current index from the first file. 我的代码从TextBox1中获取一个文件名,打开该文件并通过B列中的所有唯一值建立索引。然后,它获取另一个文件,即TextBox2中的文件名,并根据第一个文件中的当前索引对其进行过滤。 It then takes the filtered results and copies them to a sheet in the new workbook. 然后,它将获取过滤后的结果并将其复制到新工作簿中的工作表中。 A new sheet is then generated in the new workbook to paste the next filtered result. 然后在新工作簿中生成一个新工作表,以粘贴下一个过滤结果。

My issue is that I have many rows of data and for some reason the filtered data is not be selected after many iterations. 我的问题是我有很多行数据,并且由于某些原因,经过多次迭代后未选择过滤后的数据。 My program selects all filtered data when it starts, but at some point it just begins selecting the headers instead of all the visible cells. 我的程序在启动时会选择所有已过滤的数据,但是在某个时候它只是开始选择标题而不是所有可见的单元格。 Let me know if I am missing something or if there is a quick workaround. 让我知道我是否缺少某些东西或是否有快速的解决方法。 Thank you. 谢谢。

Sub NewFileGenerate()
Dim I As Integer
Dim N As Integer
Dim X As Integer
Dim IndexedCell As String

X = 1

Windows(TextBox1.Value).Activate
'Need to count only populated cells
I = Sheets(1).Columns(2).Cells.SpecialCells(xlCellTypeConstants).Count
Set Newbook = Workbooks.Add
For N = 2 To I - 1
    Application.CutCopyMode = True

    Windows(TextBox1.Value).Activate
    IndexedCell = Cells(N, 2).Value
    Windows(TextBox2.Value).Activate
    With Sheets(1)
        With .Range("A1", "Z" & I - 1)
            .AutoFilter Field:=5, Criteria1:=IndexedContract
            .SpecialCells(xlCellTypeVisible).Copy
        End With
    End With
    Newbook.Activate
    ActiveSheet.Paste Destination:=Sheets(X).Range("A1:Z1")
    Cells.Select
    Selection.Font.Size = 10
    Cells.EntireColumn.AutoFit
    Cells.Select
    X = X + 1
    If X > 3 Then
        Worksheets.Add(After:=Worksheets(Worksheets.Count)).Name = "Sheet" & X
    End If
    Application.CutCopyMode = False

Next N

End Sub

I'm guessing that your source worksheet (textbox2.value) has more rows than your index worksheet (textbox1.value). 我猜您的源工作表(textbox2.value)具有比索引工作表(textbox1.value)更多的行。 You set I equal to the number of rows in your index worksheet, then you tell the autofilter to only use that number of rows. 您将I设置为等于索引工作表中的行数,然后告诉自动筛选器仅使用该行数。 You need to change the line "With .Range("A1", "Z" & I - 1)" so it picks up all of the rows in your source worksheet. 您需要更改“ With .Range(“ A1”,“ Z”&I-1)“行,以便它可以拾取源工作表中的所有行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM