[英]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.