【问题标题】:VBA scripting for MS excelMS excel 的 VBA 脚本
【发布时间】:2017-02-17 07:54:12
【问题描述】:

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

您的帮助将不胜感激!

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    我认为这就是您的意思,以下代码循环遍历所有包含数据的行,并为每一行检查单词“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
    

    【讨论】:

    • 谢谢!!这就是我在看的。我让代码在删除点(。)的情况下运行。例如:- LastRow = 此处已​​删除点 Cells(Rows.Count, "B")....
    猜你喜欢
    • 1970-01-01
    • 2015-06-13
    • 1970-01-01
    • 1970-01-01
    • 2014-11-20
    • 2014-08-25
    • 2018-12-15
    • 2015-12-08
    • 2012-10-19
    相关资源
    最近更新 更多