附加的代码是在VBA上运行的,但是我不明白为什么会出现错误,如果没有if或者如果没有结束,则说明。我很确定如果使用if语句,我已经匹配到每一端。
Sub teee()仅用于测试decimalize函数。它将大大检查代码并告诉我我的代码有什么问题...如果我可以对此功能进行故障排除,我几乎完成了一个项目。
Sub teee()
sss = "-1-21+"
MsgBox (decimalize(sss))
End Sub
Function decimalize(s As Variant) As Long
Dim checkers As Variant
Dim ab As Long
Dim leftnum As Long
Dim rightnum As Long
Dim poneg As Integer
checkers = s
ab = 0
leftnum = 0
rigntnum = 0
poneg = 0
'Positive payup or negative payup
If Left(checkers, 1) = "-" Then
poneg = 1
lencheckers = Len(checkers)
checkers = Mid(checkers, 2, lencheckers - 1)
Else: poneg = 0
End If
startp = InStr(checkers, "-")
If startp = 2 Then leftnum = Left(checkers, 1)
ElseIf startp = 3 Then leftnum = Left(checkers, 2)
ElseIf startp = 4 Then leftnum = Left(checkers, 3)
End If
rightnum = Mid(checkers, startp + 1, 2)
If InStr(checkers, "+") > 0 Then
ab = 0.5
ElseIf InStr(checkers, "1/4") > 0 Then
ab = 0.25
ElseIf InStr(checkers, "1/8") > 0 Then
ab = 0.125
End If
rightnum = rightnum + ab
If poneg = 0 Then
decimalize = rightnum + leftnum * 32
ElseIf poneg = 1 Then
decimalize = (rightnum + leftnum * 32) * -1
End If
End Function
非常感谢提前
答案 0 :(得分:2)
像这样改变:
If startp = 2 Then
leftnum = Left(checkers, 1)
ElseIf startp = 3 Then leftnum = Left(checkers, 2)
ElseIf startp = 4 Then leftnum = Left(checkers, 3)
End If
信息:当您在同一行上的“then”之后写入结果时,不应该写入end if。因此,VBA不了解下一个ElseIf的来源。
您可以使用以下两个示例:
'Example 1 (no end if here)
if startp = 2 then leftnum = Left(checkers,1)
'Example 2 (you need end if here)
if startp = 2 then
leftnum = Left(checkers,1)
end if
答案 1 :(得分:2)
@Vityata展示了一种消除特定错误的方法。另一种方法是完全避免使用If
并使用Select Case
。生成的代码更具可读性:
Select Case startp
Case 2: leftnum = Left(checkers, 1)
Case 3: leftnum = Left(checkers, 2)
Case 4: leftnum = Left(checkers, 3)
End Select
此外,您有一个任意模式来声明某些变量而不是其他变量,并且您至少有一个变量拼写错误:rigntnum = 0
几乎肯定应该是rightnum = 0
。您确实需要在所有模块的顶部使用Option Explicit
(同样,在VBA编辑器选项中启用Require Variable Declaration
)。这将有助于您编写不容易出现随机错误的代码。