gpt4 book ai didi

excel - VBA抛出 'else without if'错误

转载 作者:行者123 更新时间:2023-12-02 23:36:19 24 4
gpt4 key购买 nike

我正在尝试以下代码,它反复抛出“else without if”和此类类似的错误。我只是无法找出错误所在,因为每个 if 都被正确终止。

这是代码:

Sub hra_macro()

Dim city As Boolean
Dim salary As Integer
Dim varHRA As Integer
Dim mimHRA As Integer
Dim maxHRA As Integer
Dim A As Integer
Dim B As Integer
Dim Rent As Integer

city = Range("b1").Value
salary = Range("b2").Value
Rent = Range("b3").Value

If city = True Then

varHRA = 0

A = Rent - (salary / 10)
B = salary * 0.5
Do While varHRA < salary
varHRA = varHRA + 1
If (varHRA < A And varHRA < B) Then
minHRA = varHRA
End If
If (A < varHRA And A < B) Then
minHRA = A
End If
If (B < varHRA And B < A) Then
minHRA = B
End If
If minHRA > maxHRA Then
maxHRA = minHRA
End If
Exit Do
Else '<<<<<<<<<<<<<<<<<<<< PROBLEM AREA

varHRA = 0

A = Rent - (salary / 10)
B = salary * 0.4
Do While varHRA < salary
varHRA = varHRA + 1
If (varHRA < A And varHRA < B) Then
minHRA = varHRA
End If
If (A < varHRA And A < B) Then
minHRA = A
End If
If (B < varHRA And B < A) Then
minHRA = B
End If
If minHRA > maxHRA Then
maxHRA = minHRA
End If
Exit Do
End If

Range("b4").Value = maxHRA

End Sub

最佳答案

乍一看,If 看起来不错,但我注意到两个 Do 都缺少 Loop

它应该看起来像这样:

Do While varHRA < salary
'Do Stuff
Loop

Exit Do 用于在 While 后面的条件为 true 之前退出循环,但您始终需要 Loop 关键字。

如果问题仍然存在,请发布您收到的确切错误消息。

<小时/>

编辑:

我只是尝试在 MS Access 中用 VBA 重现您的问题(我在这台计算机上没有安装 Excel,仅安装了 Access):

Public Function Test()

If 1 = 0 Then

Do While 1 = 0

Stop

Exit Do

Else

Stop

End If

End Function

这段简单的代码给了我与您得到的完全相同的错误消息:

Compile error: Else without If

当我用 Loop 替换 Exit Do 时,错误消失并且代码编译。

因此,您应该在代码中将 Exit Do 替换为 Loop

关于excel - VBA抛出 'else without if'错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7625746/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com