有没有办法从一个工作表中搜索和导出(排序)行到另一个工作表?
我有一个存储行列表的工作表。
我需要搜索和导出(排序)包含特定关键字的行。
例如," AAA"和" CCC"是关键字
工作表1(原件):
A B C D
AAA 123 01/mm/yyyy
BBB 456 02/mm/yyyy
CCC 789 03/mm/yyyy
AAA 123 04/mm/yyyy
工作表2(已排序):
A B C D
AAA 123 01/mm/yyyy
AAA 123 04/mm/yyyy
CCC 789 03/mm/yyyy
ps:包含" 123"的行将被归为一类
任何帮助都会得到很大的帮助,感谢您的阅读。
答案 0 :(得分:0)
有许多不同的方法可以实现这一目标。我将在下面列出其中两个。严格地说,您不需要像在此处看到的那样多的步骤来限定您的参考资料,但我已经这样做以帮助您理解。当使用两个不同的工作簿时,Excel必须确切地知道您正在引用哪些工作簿
<强> 1。使用自动过滤器
这是迄今为止最快的方法,特别是如果你有一个大数据集
Sub MoveSpecificRows3()
Dim sourceWorkbook As Workbook, destinationWorkbook As Workbook
Dim sourceWorksheet As Worksheet, destinationWorksheet As Worksheet
Dim sourceRange As Range, destinationRange As Range, r As Range
'get your workbooks
Set sourceWorkbook = ThisWorkbook
Set destinationWorkbook = Workbooks.Open("C/My Documents/.../myfile.xlsx")
'get your worksheets
Set sourceWorksheet = sourceWorkbook.Worksheets("Sheet1")
Set destinationWorksheet = destinationWorkbook.Worksheets("Sheet1")
'get your ranges
Set sourceRange = sourceWorksheet.Range("A1:D10")
Set destinationRange = destinationWorksheet.Range("A1")
'filter on values and copy/paste them over
With sourceRange
.Sort key1:=.Columns(1), order1:=xlAscending, key2:=.Columns(2), order2:=xlAscending, Header:=xlYes
.AutoFilter Field:=1, Criteria1:="=AAA", Operator:=xlOr, Criteria2:="=CCC"
.SpecialCells(xlCellTypeVisible).Copy destinationRange
sourceWorksheet.AutoFilterMode = False 'remove the filter
End With
Application.CutCopyMode = xlCopy
End Sub
<强> 2。遍历源工作簿中的每一行
设置与上述相同,但这次使用For
循环来检查每行的条件
Sub MoveSpecificRows2()
Dim sourceWorkbook As Workbook, destinationWorkbook As Workbook
Dim sourceWorksheet As Worksheet, destinationWorksheet As Worksheet
Dim sourceRange As Range, destinationRange As Range, r As Range
'get your workbooks
Set sourceWorkbook = ThisWorkbook
Set destinationWorkbook = Workbooks.Open("C/My Documents/.../myfile.xlsx")
'get your worksheets
Set sourceWorksheet = sourceWorkbook.Worksheets("Sheet1")
Set destinationWorksheet = destinationWorkbook.Worksheets("Sheet1")
'get your ranges
Set sourceRange = sourceWorksheet.Range("A1:D10")
Set destinationRange = destinationWorksheet.Range("A1")
'sort your data
With sourceRange
.Sort key1:=.Columns(1), order1:=xlAscending, key2:=.Columns(2), order2:=xlAscending, Header:=xlYes
End With
'loop through each row in your source workbook and move over when AAA or CCC found
For Each r In sourceRange.Rows
Select Case r.Cells(1, 1)
Case "AAA", "CCC"
destinationRange.Resize(1, r.Columns.Count).Value = r.Value
Set destinationRange = destinationRange.Offset(1, 0)
End Select
Next r
End Sub
destinationWorkbook
已经打开,则无需使用Workbooks.Open()
电话。用这个替换该行:
Set destinationWorkbook = Workbooks("myfile.xlsx")
注意2 我还对sourceWorkbook
中的数据进行了排序,以确保传输到destinationWorkbook
的所有值也都已排序。这假设您有数据标题。如果没有,请将header
属性更改为header:=xlNo
。