2016-10-08 93 views
-5

Image added as example我正在爲MS excel編寫一個涉及多種功能的VBA腳本。 我被困在這一點。舉一個粗略的例子: -針對MS excel的VBA腳本

如果我有一個擁有這些數據的excel,我想選擇那些在開始/中間/結尾處存在「man」(不區分大小寫)的值,併爲這些行賦值。

輸入練成

Serial Name 
1  superman 
2  spiderman 
3  Thor 
4  Hulk 
5  Captain America 
6  Mandrake 

輸出繼電器的Excel應該是:

Serial Name    Found man 
1  superman   Hello 
2  spiderman   Hello 
3  Thor  
4  Hulk  
5  Captain America 
6  Mandrake   Hello 

我只想VBA腳本,因爲它涉及到各種其他複雜和功能。所以,請不要使用Excel公式。

我試過使用Range.Find函數,但是我不能將「Hello」指定給下一個單元格。

您的幫助將非常感謝!

回答

0

我認爲這就是你的意思,下面的代碼循環遍歷所有包含數據的行,並且每行檢查單詞「man」是否在該字符串中(使用Instr函數)。

Sub FindMan() 

Dim FindString     As String 
Dim Sht       As Worksheet 

Dim LastRow      As Long 
Dim lRow      As Long 

' modify "Sheet1" to your sheet name 
Set Sht = ThisWorkbook.Sheets("Sheet1") 

With Sht 
    ' find last row in Column "B" 
    LastRow = .Cells(.Rows.Count, "B").End(xlUp).Row 

    ' you can modify your searched word as you wish at the following line 
    FindString = "man" 

    ' loop through all rows with data in cells "B" 
    For lRow = 2 To LastRow 
     If InStr(1, .Cells(lRow, 2), FindString, vbTextCompare) > 0 Then 
      .Cells(lRow, 3).Value = "Hello" ' if found add "Hello" to the cell on the right > Column C 
     End If 
    Next lRow 

    ' add header title for Column C 
    .Cells(1, 3).Value = "Found man"  
End With 

End Sub 
+0

謝謝! 這就是我正在看的。我使用點(。)的刪除運行代碼。例如: - LastRow = *這裏刪除點*單元格(Rows.Count,「B」).... – Prashant