【问题标题】:Find text "testing" in a particular cell and check condition在特定单元格中查找文本“测试”并检查条件
【发布时间】:2016-11-26 08:05:57
【问题描述】:

我在“F”列中有一些描述文本。例如是

f1= P&PES - INTEROPERABILITY TESTING & VALIDATION SRVCS 
f2= CMT-PEL-PRODUCT ENGINEERING 
f3 = AO-TESTING-TESTING EXCELLENCE

现在我想运行一个循环,它将考虑单个单元格并检查特定单元格中的值是否包含“测试”。

如果它包含“测试”,那么我想执行一些条件。

如果它不包含“测试”字样,那么将检查下一个单元格,就像检查 f2 一样,依此类推。

循环应该一直持续到有值为止。下面是我编写的代码,但它仅在第一次在 f1 中找到值 testing 时才起作用,当它检查 f2 时它没有找到测试字然后它抛出一个错误错误。“对象变量或块变量不是设置”并且宏停止。

代码如下:

Dim Atdes As Integer
Dim Lamt As Integer
Dim Tcr As Integer

OG = 2
Oid = 3
row1 = 3
Lamt = 10
Tcr = 12
Atdes = 6
columnAA = 27
columnAB = 28
columnAC = 29
columnAD = 30
columnAE = 31

Do While Sheets("BH_Testing Practice_0_FY17_Sale").Cells(row1, 1).Value <> ""

    ' To find testing word
    Sheets("BH_Testing Practice_0_FY17_Sale").Cells(row1, 6).Select
    If Selection.find(What:="testing", After:=ActiveCell, LookIn:=xlFormulas, _
        LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
        MatchCase:=False, SearchFormat:=False).Activate Then

        Sheets("BH_Testing Practice_0_FY17_Sale").Cells(row1, columnAA).Value = "CAT"
    End If
    row1 = row1 + 1
Loop

End Sub

【问题讨论】:

  • 您是否只想在一个单元格Cells(row1, 6) 中找到“测试” - 一个包含当前行“F”列的单元格?还是整行?
  • 试试我下面答案中的代码,看看它是否适合你
  • 您是否测试了您得到的任何答案?一些反馈会很好
  • 是的,来自 clintB 的那个为我工作,谢谢
  • 您确实意识到在您的情况下InstrLike 函数的行为相同?无论如何,通过点击他答案旁边的小V来接受他的答案

标签: vba excel


【解决方案1】:

使用 instr 代替搜索。它更易于使用。

 set ws = Sheets("BH_Testing Practice_0_FY17_Sale")

 If( InStr(ws.Cells(row1, 1), SearchStr))>0) THEN
     ...
 END IF

很像最近对这个问题发表的评论: Excel VBA Check for specific value in cell

【讨论】:

    【解决方案2】:

    使用Like 函数可以查看某个单元格中是否包含“testing”字符串。在“testing”前后加上通配符(*)表示“testing”也可以出现在整个单元格字符串的开头或结尾。

    (我注释了代码中的一些cariables,不是为了报错)

    代码

    Option Explicit
    
    Sub FindTesting()
    
    Dim Atdes As Integer
    Dim Lamt As Integer
    Dim Tcr As Integer
    Dim row1    As Long
    Dim columnAA As Integer
    
    'OG = 2
    'Oid = 3
    row1 = 3
    Lamt = 10
    Tcr = 12
    Atdes = 6
    columnAA = 27
    'columnAB = 28
    'columnAC = 29
    'columnAD = 30
    'columnAE = 31
    
    With Sheets("BH_Testing Practice_0_FY17_Sale")
        Do While .Cells(row1, 1).Value <> ""
            ' check if current row Column F contains "testing"
            If .Cells(row1, 6) Like "*testing*" Then
                .Cells(row1, columnAA).Value = "CAT"
            End If
    
            row1 = row1 + 1
        Loop
    End With
    
    End Sub
    

    【讨论】:

      猜你喜欢
      • 2016-06-17
      • 1970-01-01
      • 2012-10-31
      • 1970-01-01
      • 2012-10-13
      • 1970-01-01
      • 1970-01-01
      • 2013-08-28
      • 2020-01-28
      相关资源
      最近更新 更多