2012-05-14 26 views
0

我有一个电子表格,其中包含A-P和第1到2016行(并且仍在不断增长)的列。我正在寻找一种简单的方法来搜索电子表格中的特定单词,例如“间隙”,并将包含单词“间隙”的行复制到Sheet2。我想如果它可以使用一个框,我可以根据需要搜索不同的东西。搜索一个特定的单词并将其复制到另一个工作表

我不希望电子表格变得更小(这是一个行动项目列表,我需要它搜索,直到它到达一个空行)。

我该怎么做?

回答

1
'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 
+0

您的代码将是伟大的关于如何使用一些意见和解释,使(似乎谁不知道VBA孔)OP会知道从哪里开始 – JMax

+0

好吧,我会在我重建它回到家里,现在我在工作:D –

+0

@MarcinJanowski我认为JMax意味着你的回答应该包括解释(对问题的“答案”),而不仅仅是代码。 – yoozer8

相关问题