If语句在for循环VBA中

时间:2019-09-25 22:05:16

标签: excel vba loops if-statement

我想让我的函数跳过我的字符串中没有出现的列表中的单词,但这似乎不起作用

我尝试使用VBA和excel本机命令...但是我得到了相同的结果

Public Function test(range, y)

step = y

For Each cell In range

If InStr(cell, step, vbTextCompare) <> 0 Then

step = Application.WorksheetFunction.Replace(step,Application.WorksheetFunction.Search(cell, step), Len(cell), UCase(cell))

test = step
End If
Next cell

End Function

当我尝试在Excel中使用此函数时,我得到#VALUE,我怀疑这是因为并非在字符串中找到列表中的所有值,但是那是if语句的原因

1 个答案:

答案 0 :(得分:0)

首先,在Instr中将变量向后移动。如果使用最后一个,则必须使用firs标准。

此外,如果您要查找完整的单词,则需要在搜索和替换上使用" "

最后使用vba的替换:

Public Function test(rng As range, y As String)
    Dim step As String
    step = y

    Dim cell As range
    For Each cell In rng
        If InStr(1, " " & step & " ", " " & cell & " ", vbTextCompare) > 0 Then
            step = Replace(" " & step & " ", " " & cell & " ", UCase(" " & cell & " "))
        End If
    Next cell

    test = Application.Trim(step)

End Function

enter image description here

相关问题