循环遍历主表并过滤掉需要的行

循环遍历主表并过滤掉需要的行

我创建了一个脚本,我想让用户选择一个文件(主文件),如果满足条件,我想将数据复制到 excel 工作簿(脚本在其上运行)下面的代码显示了我想要做的事情。目前 if 语句只检查 A2 是否包含值 5。我希望它检查列中的每一行,而不仅仅是一个单元格。

Sub copyData()
Dim FolderPath As String, Filepath As String, Filename As String

 FolderPath = Application.GetOpenFilename(FileFilter:="Excel Files (*.XLS*),  
 *.XLS*", Title:="Select File To Be Opened")
 Dim numTest As Integer

Filename = Dir(FolderPath)

Dim lastrow As Long, lastcolumn As Long

Do While Filename <> ""

Workbooks.Open (FolderPath)
numTest = ActiveSheet.Range("A2").Value
lastrow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row
lastcolumn = ActiveSheet.Cells(1, Columns.Count).End(xlToLeft).Column
Range(Cells(1, 1), Cells(lastrow, lastcolumn)).Copy
Application.DisplayAlerts = False
ActiveWorkbook.Close

erow = Sheet1.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
MsgBox "Testing: " & ActiveSheet.Name & " " & Cells(2, 1).Value & " is >= 5"
If numTest >= 5 Then
ActiveSheet.Paste Destination:=Worksheets("Sheet1").Range(Cells(erow, 1),   
Cells(erow, 10))
Else
MsgBox ("test1")
End If
Filename = Dir
Loop

End Sub

我还想出了如何选择要复制的范围:

    Range(Cells(1, 1), Cells(lastrow, lastcolumn)).Copy

我怎样才能改变这一点以便只复制特定的列?

答案1

你还有一段路要走,但看起来并不是那么糟糕:)

这里有一些技巧可以让您更轻松地编写代码:

  1. 将每个工作表存储为一个变量,这样可以更容易地看到从哪个工作表中获取数据:

    Dim wbMaster As Workbook, wbCurrent As Workbook
    
    Set wbCurrent = ActiveWorkbook
    Set wbMaster = Workbooks.Open(FolderPath)
    
  2. 在主表中命名您的工作表以使其更易于引用(在 VB 中按 F4 查看工作表属性):

    numTest = wbMaster.SHEETCODENAME.Range("RANGENAME").Value
    lastrow = wbMaster.Cells(Rows.Count, 1).End(xlUp).Row 
    lastcolumn = wbMaster.Cells(1, Columns.Count).End(xlToLeft).Column
    
  3. 如果您将主数据存储为表格,那么这对您来说会更容易,通过谷歌搜索您会发现单元格和列变得更加容易引用。

  4. 一次性完成粘贴和复制(运行宏时最好不要选择任何范围

    wbMaster.SHEETCODENAME.Range("A:A").Copy _
        Destination:=wbCurrent.SHEETCODENAME.PasteSheet.Range("B:B")
    
  5. 检查选定范围内的每一行:

    Dim rw As Range
    
    For Each rw In wbMaster.SHEETCODENAME.Range("RANGENAME").Rows
        'Do something
    Next rg
    

相关内容