繁体   English   中英

在for循环中嵌套if语句

[英]Nested if statement within a for loop

我正在修改我写的用户定义函数。 它从一个单元格中删除了特殊字符(我已经发布了几次相同的函数,因为我不断扩展它并学习更多关于VBA的功能)。

我现在要做的是添加一个弹出的MsgBox,并告诉用户exactley删除了哪些特殊字符。 我认为我可以通过使用嵌套在我现有的for循环中的If语句来实现这一点,如下所示:

Function removeSpecial(sInput As String) As String
    Dim sSpecialChars As String
    Dim i As Long
    Dim sReplaced As String
    sSpecialChars = "\/:*?™""®<>|.&@# %(_+`©~);-+=^$!,'" 'This is your list of characters to be removed
    For i = 1 To Len(sSpecialChars)
        sInput = Replace$(sInput, Mid$(sSpecialChars, i, 1), "")
        If (sInput = sSpecialChars) Then 'If statement to check when a character has been removed
        sReplaced = sInput 'String variable to store each special character which was replaced
    Next
    MsgBox sReplaced & " These were removed"
    sInput = UCase(sInput)
    removeSpecial = sInput

End Function 'end of function

目前这让我陷入了一个无限循环,我必须强制关闭Excel。 我试图用上面的代码做的是检查一个单独的字符是否位于Mid函数当前正在查看的任何索引处,然后将该字符(如果被替换)保存到String sReplaced。 显然,我在我的脑海里。

谢谢你的帮助。

请检查此版本:

Function removeSpecial(sInput As String) As String

    Dim sSpecialChars As String, sTemp As String
    Dim i As Long
    Dim sReplaced As String
    sTemp = sInput
    sSpecialChars = "\/:*?™""®<>|.&@# %(_+`©~);-+=^$!,'"

    For i = 1 To Len(sSpecialChars)
        ch = Mid(sSpecialChars, i, 1)
        If InStr(sTemp, ch) > 0 Then
            sTemp = Replace$(sTemp, ch, "")
            sReplaced = sReplaced & ch
        End If
    Next

    MsgBox sReplaced & " These were removed"
    sTemp = UCase(sTemp)
    removeSpecial = sTemp
End Function

注意:这不会尝试修改输入,只返回“已清理”的输出字符串。

试试这个:

Function removeSpecial(sInput As String) As String
    Dim sSpecialChars As String
    Dim i As Long
    Dim sReplaced As String
    Dim ln As Integer

    sSpecialChars = "\/:*?™""®<>|.&@# %(_+`©~);-+=^$!,'" 'This is your list of characters to be removed
    For i = 1 To Len(sSpecialChars)
        ln = Len(sInput)
        sInput = Replace$(sInput, Mid$(sSpecialChars, i, 1), "")
        If ln <> Len(sInput) Then sReplaced = sReplaced & Mid$(sSpecialChars, i, 1)
    Next
    MsgBox sReplaced & " These were removed"
    sInput = UCase(sInput)
    removeSpecial = sInput

End Function 'end of function

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM