'Range' 的 object'_Global' 在 Do Until 中失败

'Range' of object'_Global' fail in Do Until

基本上我只是在网上找到这个小代码,我认为它可能对我有帮助,因为我想改进它。但是在

Do Until Range("A" & amp, R) = ""

行我在标题中遇到了提到的错误。

代码如下:

Sub Use_Instr()
    R = 1
    'loop to the last row
    Do Until Range("A" & amp, R) = ""
        'check each cell if contains 'apple' then..
        '..place 'Contains Apple' on column B
        If Range("A" & amp, R) Like "*apple*" Then
            Range("B" & amp, R) = "Contains Apple"
        End If
        R = R + 1
    Loop
End Sub

它确实在 A 列的句子中搜索“apple”字词,并在 B 列中写下“contains apple” 包含“apple”的列

试试这个:

R = 1
'loop to the last row
Do Until Range("A" & R).Value = ""
'check each cell if contains 'apple' then..
'..place 'Contains Apple' on column B
If Range("A" & R).Value Like "*apple*" Then
    Range("B" & R).Value = "Contains Apple"
End If
R = R + 1
Loop

Range("A" & amp, R) 不是解决范围的正确方法。当您从网站复制时,它也复制了 html 编码。在 Html 中,& 被编码为 &。只需在您的代码中将 & amp, 替换为 & 即可。所以你的代码变成

R = 1
'loop to the last row
Do Until Range("A" & R) = ""
    'check each cell if contains 'apple' then..
    '..place 'Contains Apple' on column B
    If Range("A" & R) Like "*apple*" Then
        Range("B" & R) = "Contains Apple"
    End If
    R = R + 1
Loop

另外,为了使代码不区分大小写,正如@VBasic2008 在下面的评论中所建议的,您可能需要将 Range("A" & R) Like "*apple*" 更改为 If LCase(Range("A" & R).Value2) Like "*apple*" Then

话虽如此,我会使用与使用循环稍慢的方法不同的方法。

It does search the "apple" term in the sentences in A column and write "contains apple" in the B column if it contains "apple"

如果您要在 Excel 中执行此操作,那么您将使用公式 =IF(ISNUMBER(SEARCH("apple",A1)),"Contains Apple","")

所以我们要做的是找到第 B 列的最后一行,然后在 的整个范围内添加这个公式 !最后我们将公式转换为数值。

Option Explicit

Sub Sample()
    Dim ws As Worksheet
    Dim lRow As Long
    Dim sFormula As String
    
    '~~> Change this to the relevant sheet
    Set ws = Sheet1
    
    '~~> This is your formula
    '   =IF(ISNUMBER(SEARCH("apple",A1)),"Contains Apple","")
    sFormula = "=IF(ISNUMBER(SEARCH(""apple"",A1)),""Contains Apple"","""")"
    
    With ws
        '~~> Find the last row in column B
        lRow = .Range("A" & .Rows.Count).End(xlUp).Row
        
        '~~> Insert the formula in the entire range in 1 go
        With .Range("B1:B" & lRow)
            .Formula = sFormula
            '~~> Convert formula to value
            .Value = .Value
        End With
    End With
End Sub