0

AP から 1 行目から 2016 行目までの列で構成されるスプレッドシートがあります (まだ拡大中です)。「ギャップ」などの特定の単語をスプレッドシートで検索し、「ギャップ」という単語を含む行を Sheet2 にコピーする簡単な方法を探しています。必要に応じてさまざまなものを検索できるように、単語を入れるボックスを使用できるといいのですが。

スプレッドシートがこれ以上小さくなるとは思いません (これはアクション アイテムのリストです。空白行に達するまで検索する必要があります)。

これどうやってするの?

4

1 に答える 1

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
于 2012-05-14T22:34:36.303 に答える