【问题标题】:If Statement in for loop VBAfor循环VBA中的If语句
【发布时间】:2019-09-25 22:05:16
【问题描述】:

我想让我的函数跳过我的列表中不在我的字符串中但它似乎不起作用的单词

我尝试过使用 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 语句的原因

【问题讨论】:

  • 您不应使用range 作为变量名。 y 的值是多少?
  • 不是你的问题,但是,使用 VBA 的替换:step = Replace(step, cell, UCase(cell)) 并且你的指令是向后的:If InStr(step, cell, vbTextCompare) &lt;&gt; 0 Then
  • 您好,Well Range 是 Excel 中定义的列表,y 是包含字符串的单元格
  • 嗨,斯科特,交换了变量,但仍然没有运气:(
  • Ummm...你怎么有一个函数不设置“测试”函数本身的值?这不能保证函数的值是 #VALUE 吗?如果您只想运行替换而不是返回值,我不确定这应该是一个函数。

标签: excel vba loops if-statement


【解决方案1】:

首先,您在 Instr 中有向后的变量。如果使用最后一个标准,则必须使用第一个标准。

此外,如果您正在寻找完整的单词,那么您需要在搜索和替换时使用" "

最后使用 vba 的 Replace:

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

【讨论】:

  • 嗨斯科特,非常感谢!像魅力一样工作。我是在 Excel 中使用 VBA 的新手。我会花时间去理解和学习。谢谢! :)
猜你喜欢
  • 1970-01-01
  • 2019-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-26
  • 1970-01-01
  • 2016-06-16
  • 2019-06-09
相关资源
最近更新 更多