我有一个电子表格,其中包含从 AP 和第 1 行到 2016 年的列(并且仍在增长)。我正在寻找一种简单的方法来搜索电子表格中的特定单词,例如“Gap”,并将包含单词“gap”的行复制到 Sheet2。我想它是否可以使用我输入单词的框,以便我可以根据需要搜索不同的内容。
我不希望电子表格变得更小(这是一个操作项列表,我需要它进行搜索,直到它到达一个空白行)。
我怎样才能做到这一点?
'all variables must be declared
Option Explicit
Sub CopyData()
'this variable holds a search phrase, declared as variant as it might be text or number
Dim vSearch As Variant
'these three variables are declared as long, technically the loop might exceed 32k (integer) therefore it is safer to use long
Dim i As Long
Dim k As Long
Dim lRowToCopy As Long
'the macro prompts a user to enter the search phrase
vSearch = InputBox("Search")
'varialbe i initially declared as 1 - macro starts calculations from the 1st row
i = 1
'macro will loop until it finds a row with no records
'I called a standard XLS function COUNTA to count the number of non-blank cells
'if the macro finds a row with no records it quits the loop
Do Until WorksheetFunction.CountA(Sheets("Main").Rows(i)) = 0
'here I let the macro to continue its run despite a possible errors (explanation below)
On Error Resume Next
lRowToCopy = 0
'if Find method finds no value VBA returns an error, this is why I allowed macro to run despite that. In case of error variable lRowToCopy keeps 0 value
'if Find method finds a searched value it assigns the row number to var lRowToCopy
lRowToCopy = Sheets("Main").Rows(i).Find(What:=vSearch, LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByRows).Row
'here we allow macro to disiplay error messages
On Error GoTo 0
'if var lRowToCopy does not equal to 0 that means a row with a searched value has been found
If lRowToCopy > 0 Then
'this loop looks for the first blank row in 2nd sheet, I also used COUNTA to find absolutely empty row
For k = 1 To Sheets("ToCopy").Rows.Count
'when the row is found, the macro performs copy-paste operation
If WorksheetFunction.CountA(Sheets("ToCopy").Rows(k)) = 0 Then
Sheets("Main").Rows(i).Copy
Sheets("ToCopy").Select
Rows(k).Select
ActiveSheet.Paste
'do not forget to exit for loop as it will fill all empty rows in 2nd sheet
Exit For
End If
Next k
End If
i = i + 1
Loop
End Sub