RaoVat24h
Excel Office

BÀI 4 DÙNG IF THEN ELSE TRONG VBA

Advertisement

Cấu trúc lệnh

If Điều kiện 1 Then
Biểu thức 1
Elseif  Điều kiện 2  then
Biểu thức 2
Else
Biểu thức 3
End If

Điều kiện

  • Toán tử
=  bằng
> Lớn hơn
< nhỏ hơn
>= Lớn hơn hoặc bằng
<= Nhỏ hơn hoặc bằng
<> khác
  • Logic
And  Và
or Hoặc
Xor cả 2 đúng hoặc sai là đúng
Not phủ định

Ví dụ 1
Private Sub CommandButton1_Click()
Dim firstnum, secondnum As Single
firstnum = Cells(1,1).Value
secondnum = Cells(1,2).Value
If firstnum>secondnum Then
  MsgBox “ The first number is greater than the second number”
If firstnum<secondnum Then
  MsgBox “ The first number is less than the second number”
Else
  MsgBox “ The two numbers are equal ”
End If
End Sub
Ví dụ 2
Private Sub CommandButton1_Click()
Dim mark As Integer
Dim grade As String
mark = Int(Rnd * 100)
Cells(1, 1).Value = mark
If mark < 20 And mark >= 0 Then
grade = “F”
Cells(2, 1).Value = grade
ElseIf mark < 30 And mark >= 20 Then
grade = “E”
Cells(2, 1).Value = grade
ElseIf mark < 40 And mark >= 30 Then
grade = “D”
Cells(2, 1).Value = grade
ElseIf mark < 50 And mark >= 40 Then
grade = “C-“
Cells(2, 1).Value = grade
ElseIf mark < 60 And mark >= 50 Then
grade = “C”
Cells(2, 1).Value = grade
ElseIf mark < 70 And mark >= 60 Then
grade = “C+”
Cells(2, 1).Value = grade
ElseIf mark < 80 And mark >= 70 Then
grade = “B”
Cells(2, 1).Value = grade
ElseIf mark <= 100 And mark > -80 Then
grade = “A”
Cells(2, 1).Value = grade
End If
End Sub

Hướng dẫn chi tiết:

?DienDan.Edu.Vn cám ơn bạn đã quan tâm và rất vui vì bài viết đã đem lại thông tin hữu ích cho bạn. https://diendan.edu.vn/
?Thanks

Rate this post

DienDan.Edu.Vn

DienDan.Edu.Vn Cám ơn bạn đã quan tâm và rất vui vì bài viết đã đem lại thông tin hữu ích cho bạn.
DienDan.Edu.Vn! là một website với tiêu chí chia sẻ thông tin,... Bạn có thể nhận xét, bổ sung hay yêu cầu hướng dẫn liên quan đến bài viết. Vậy nên đề nghị các bạn cũng không quảng cáo trong comment này ngoại trừ trong chính phần tên của bạn.
Cám ơn.

Đăng bình luận

(+84) (901) 369.468