我想将具有特定结构的 if 条件检查为字符串,但在 1 个已知字符串之后使用变量



>我有一个字符串(例如:blaZ-34blalba -$'34 ZBG-1004 Zblablabla)。 我知道我需要的字符串形式为 Z$$-%%%%,其中 $ 为字符串,% 为整数,字符串的长度也将为 8 长。 我需要把这根绳子拆开。 这是我尝试的代码(我看到%和$应该替换字符串和整数),但它似乎不起作用。

也许我只是不知道要寻找什么(我没有找到任何清洁解决方案)。

Sub test1()
Dim comment As String
Dim name As String
Dim eureka As Integer
Dim posOfZ As Integer
Sheets("Sheet1").Select
comment = Range("A1").Text
posOfZ = InStr(comment, "Z")
name = Mid(comment, posOfZ, 8)
eureka = 1
While eureka = 1
If name <> "Z$$-%%%%" Then
comment = Replace(comment, "Z", "", 1, 1)
posOfZ = InStr(comment, "Z")
name = Mid(comment, posOfZ, 8)
Else
eureka = 0
End If
Wend
End Sub

嗯...您需要创建一个函数来确定您是否具有funIsChar中的有效字符(见下文)。 如果需要,您可以修改此函数以包含任何特殊字符。 您甚至可以决定数字也可以,然后您甚至不必检查字符的有效性,因为它已经是一个字符串。

另外,不要忘记测试找不到格式的情况。 如果扫描整个字符串并且该格式不存在,则需要正常退出例程。 我将msgbox的放在代码中以显示需要异常处理的位置。

另外,最好分别检查应该是数字的 4 个字符中的每一个的IsNumeric。 如果您尝试在一个语句中一次执行所有操作,则小数将被视为有效。 (当然,如果允许使用小数,则应考虑压缩为一个语句。

另外,还有...我翻转了你eureka测试的逻辑值。 通常(在编程逻辑中)测试 0 意味着它是"假的",测试 1 是"真"。 因此,您希望在未找到值时进行循环(意味着它是假的),并在eureka变为 true 时从循环中转义(表示您已找到所需的内容)。 我还添加了一个新的布尔标志booEscapeFlag以帮助在找不到格式时退出循环。 (如果您也想将eureka变量更改为布尔值,我会将其作为练习留给您。

Sub test1()
Dim comment As String
Dim name As String
Dim eureka As Integer
Dim posOfZ As Integer
Dim booEscapeFlag As Boolean  ' New boolean escape from the loop flag
Sheets("Sheet1").Select
comment = Range("A1").Text
posOfZ = InStr(comment, "Z")
If posOfZ > 0 Then    ' Test if Z was found, if not, jump to "Z not found" message
name = Mid(comment, posOfZ, 8)
eureka = 0             ' Now set to 0 to indicate it's not found yet
booEscapeFlag = False  ' Set boolean flag to false
While eureka = 0 And Not booEscapeFlag    ' added test for not escaping yet
If funIsChar(Mid(name, 2, 1)) Then     ' "Z$$-%%%%"
If funIsChar(Mid(name, 3, 1)) Then
If Mid(name, 4, 1) = "-" Then
If IsNumeric(Mid(name, 5, 1)) Then
If IsNumeric(Mid(name, 6, 1)) Then
If IsNumeric(Mid(name, 7, 1)) Then
If IsNumeric(Mid(name, 8, 1)) Then
eureka = 1
End If
End If
End If
End If
End If
End If
End If
If eureka <> 1 Then
comment = Replace(comment, "Z", "", 1, 1)
posOfZ = InStr(comment, "Z")
If posOfZ > 0 Then           ' Test to see if next Z was found
name = Mid(comment, posOfZ, 8)
Else
MsgBox "Z$$-%%%% format not found"
booEscapeFlag = True      ' Set boolean flag to true so we can exit the loop
End If
End If
Wend
If eureka = 1 Then
MsgBox "Found it: " & name
End If
Else
MsgBox "Z not found"  ' This msg box was triggered by the first if statement at the top of the subroutine
End If
End Sub
Function funIsChar(strChr) As Boolean
Select Case Asc(strChr)
Case 65 To 90, 97 To 122   ' Ascii 65 - 90 is uppercase letters, 97 - 122 is lowercase letters.  You can add more case statements if you need to test for special characters
funIsChar = True
Case Else
funIsChar = False
End Select
End Function

希望对:)有所帮助

相关内容

最新更新