[英]Why my If condition is returning wrong result?
I'm a student currently studying VBA in one of my classes, where the current assignment is to pull data from a .txt file and display it, as well as total it, and then grade the total. 我是一名学生,目前正在我的一门课程中学习VBA,当前的任务是从.txt文件中提取数据并显示并进行总计,然后对总计进行评分。 using arrays I've been successful in the first two parts using arrays, but when trying to factor in the total for a grade the array only takes the starting numbers into account.
使用数组我在使用数组的前两个部分中已经取得了成功,但是当尝试将某个年级的总和考虑在内时,该数组仅考虑了起始数字。 Any thoughts?
有什么想法吗? Code below
下面的代码
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
Problem is with your If
condition. 问题出在您的
If
条件上。 In VBA 1 < 2 < 1
evaluates to true
. 在VBA中
1 < 2 < 1
计算为true
。 That's why even if your total(i)
is more than 100, it always evaluates to true and your elseif
is not coming into play. 这就是为什么即使您的
total(i)
大于100,它也始终评估为true,而您的elseif
却没有发挥作用。
In VBA/VB6, type conversion is simply evil. 在VBA / VB6中,类型转换简直是邪恶的。
You nee to rewrite your If
and elseif
conditions 您需要重写
If
和elseif
条件
Example: 例:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.