为什么我的If条件返回错误的结果?

我是一名正在学习VBA课程的学生,目前的任务是从.txt文件中提取数据并显示数据,然后将其总计,然后对总数进行评分。 使用数组我已经在使用数组的前两部分中取得了成功,但是当试图考虑总分数时,数组只考虑起始数字。 有什么想法吗? 下面的代码

Sub Categories() Dim Locale As String, State(1 To 50) As Variant Dim Serial(1 To 50) As Single, i As Single Dim path As String, j As Single Dim Score(1 To 50, 1 To 7) As Single Dim IndexGrade(1 To 50) As Single Dim Total(1 To 50) As Single Locale = ActiveWorkbook.path path = Locale & "US_States.txt" Open path For Input As #1 For i = 1 To 50 Step 1 Input #1, Serial(i), State(i) Sheet1.Cells(1 + i, 1).Value = Serial(i) Sheet1.Cells(1 + i, 2).Value = State(i) For j = 1 To 7 Step 1 Input #1, Score(i, j) Total(i) = Total(i) + Score(i, j) Sheet1.Cells(1 + i, 3).Value = Total(i) Next j Total(i) = Sheet1.Cells(1 + i, 3).Value If 0 <= Total(i) < 100 Then Sheet1.Cells(1 + i, 4).Value = "A" ElseIf 100 <= Total(i) < 200 Then Sheet1.Cells(1 + i, 4).Value = "B" ElseIf 200 <= Total(i) < 300 Then Sheet1.Cells(1 + i, 4).Value = "C" ElseIf 300 <= Total(i) Then Sheet1.Cells(1 + i, 4).Value = "D" End If Next i Close #1 End Sub 

问题是你的If条件。 在VBA 1 < 2 < 1评估为true 。 这就是为什么即使你的total(i)超过100,它总是评估为真,你的elseif不会发挥作用。

在VBA / VB6中,types转换简直是邪恶的。


你需要重写你的Ifelseif条件

例:

 Sub test() Dim x As Long Dim y As Long x = 101 y = 99 '/ What you are doing If 0 <= x < 1 Then MsgBox "This is not python." End If '/ How you should do it. If y >= 0 And y < 100 Then MsgBox "This is how you do it in VBA." End If End Sub