首页 文章

MS excel的VBA脚本

提问于
浏览
-5

Image added as example我正在为MS excel编写一个VBA脚本,它涉及多种功能 . 我被困在这一点上 . 举一个粗略的例子: -

如果我有一个excel有这个数据,我想选择那些在开头/中间/最后一个存在“man”(不区分大小写)并为这些行赋值的值 .

输入excel

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"分配给下一个单元格 .

非常感谢您的帮助!!

1 回答

  • 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
    

相关问题