2017-04-21 290 views
0

我已經能夠在工作表中搜索名稱(Dion在下面的代碼中),並將包含名稱Dion的行復制到不同的工作表。但是,目標工作表可能包含與源工作表中文本的最後一列相鄰或更遠的列中的文本。Excel VBA選擇單元格範圍直到單元格包含特定文本

我希望能夠從包含Dion的行中選擇一系列單元格,選擇結束於包含特定文本的單元格。

我也試過將If Cells(...).Value = "Dion" Then更改爲 If Range("A1:CS1000")...但一直得到類型不匹配錯誤。

這是我的VBA代碼。我知道這可能是非常低效的,但這是我能夠做的工作:

Dim r As Long 
Dim endRow As Long 
Dim pasteRowIndex As Long 

Worksheets("Tracking").Activate 

endRow = 500 
pasteRowIndex = 1 

For r = 6 To endRow 

    If Cells(r, Columns("BM").Column).Value = "Dion" Then 

     Rows(r).Select 
     'Code above shoud select all cells from Rows(r) until a cell contains the text "End" 
     Selection.Copy 

     Worksheets("Dion").Select 
     Rows(pasteRowIndex + 5).Select 
     ActiveSheet.Paste 

     pasteRowIndex = pasteRowIndex + 1 

     Worksheets("Tracking").Select 

    End If 

Next r 

感謝您的幫助。

+1

題外話,'細胞(r,Columns(「BM」)。Column)'你可以簡單地說'Cells(r,「BM」)' –

回答

2

如果你只是試圖限制該行的副本將上升到包含「結束」的值一列,下面的代碼應該工作:

Dim r As Long 
Dim endRow As Long 
Dim pasteRowIndex As Long 
Dim endCell As Range 

'Use With block so that we can write '.' instead of 'Worksheets("Tracking").' 
With Worksheets("Tracking") 

    endRow = 500 
    pasteRowIndex = 1 

    For r = 6 To endRow 
     'Always qualify 'Cells', 'Range', 'Columns' and 'Rows' objects so that we 
     'know what sheet we are referring to 
     'Also, as pointed out by A.S.H, ' Columns("BM").Column ' can be 
     'shortened to ' "BM" ' 
     If .Cells(r, "BM").Value = "Dion" Then 
      'Find, in the current row, the location of the first cell containing "End" 
      'Note: If you want to search for the word "End" by itself, rather than just 
      '"End" within the cell (e.g. in the value "Endymion"), change "xlPart" to 
      '"xlWhole" 
      Set endCell = .Rows(r).Find(What:="End", LookIn:=xlValues, LookAt:=xlPart, After:=.Cells(r, "A")) 
      If endCell Is Nothing Then 
       'If no "End" found, copy the entire row 
       .Rows(r).Copy Worksheets("Dion").Rows(pasteRowIndex + 5) 
      Else 
       'If "End" found, copy from column A to the cell containing "End" 
       'Note: I have assumed you don't want to copy the "End" cell itself 
       .Range(.Cells(r, "A"), endCell.Offset(0, -1)).Copy Worksheets("Dion").Rows(pasteRowIndex + 5).Cells(1, "A") 
      End If 

      pasteRowIndex = pasteRowIndex + 1 

     End If 

    Next r 
End With 
+1

非常感謝!我得到了運行時錯誤91「故障設置對象變量...」與寫的代碼。我將Set添加到以endCell開頭的代碼行中並處理它。再次感謝! – dphhaas

+0

@dphhaas - 對不起 - 是的,這是我的代碼中的錯誤。 (如果有人試圖使用它,我會更新它。) – YowE3K

相關問題