Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
467 views
in Technique[技术] by (71.8m points)

excel - VBA to find a word in a range and copy all cells beginning with the same word

I need help with my routine. I have a row (2) in which there is a number of populated cells. At one instance I have a couple (the number changes every now and again) cells consecutively starting with the word Blue (and ending with a number 1, 2 ,3 4 etc.). Ignoring the numbers, I would like to copy all cells (as a range?) starting with the word Blue*. I have managed to get one cell find and copy with the below code:

Sub findcopy()
  Dim rFound As Range
  
  Set rFound = Sheets("page 1").Rows(2).Find(What:="Blue", LookIn:=xlValues, LookAt:=xlWhole, MatchCase:=False)

If Not rFound Is Nothing Then rFound.Offset(0, 0).Resize(1).Copy Destination:=Sheets("page 1").Range("AG2")

End Sub

Thanks

question from:https://stackoverflow.com/questions/65559696/vba-to-find-a-word-in-a-range-and-copy-all-cells-beginning-with-the-same-word

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I guess this should do the job.I will try to refine it a bit more but at the moment this is working. Still, I will welcome other answers (and accept if better) and suggestions before I accept my own. Thanks

Sub SearchX()
Dim c, destination As Range, i As Long
Const SEARCH_TERM As String = "Blue"
Set destination = ActiveSheet.Range("AA10")
For Each c In ActiveSheet.Range("B2:BB2")
i = 1
Do While InStr(i, c.Value, SEARCH_TERM) > 0
destination.Value = c.Value
Set destination = destination.Offset(1, 0)
i = InStr(i, c.Value, SEARCH_TERM) + Len(SEARCH_TERM)
Loop
Next
End Sub

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...