Sunday, April 14, 2019

CÁCH DÙNG VÒNG LẬP FOR … NEXT LOOP

– Vòng lập rất hay được sử dụng trong VBA hay trong các ngôn ngữ khác vì chúng ta có thể lấy tất cả các dữ liệu thông qua nó.
– Có 2 loại vòng lập: For … Next loop và Do … Loop
– Trong bài này chúng ta có tìm hiểu kỹ vòng lập For … Next Loop
For counter=startNumber to endNumber (Step increment) 
    One or more VB statements 
Next
Ví dụ 1
Dim i As Integer
For i = 0 To 10 Step 1
Cells(i + 1, 1) = i
Next
Ví dụ 2
Dim i As Integer
For i = 1 To 15 Step 2
Cells(i, 1).Value = i
Next
Ví dụ 3
Dim i As Integer
For i = 1 To 15
Cells(i, 1) = i
If  i >= 10 Then
Exit For
End If
Next
Ví dụ 4
Dim i, j As Integer
For i = 1 To 10
For j = 1 To 5
Cells (i, j) = i + j
Next j
Next i
Ví dụ 5
Dim i, counter As Integer
For i = 1 To 20
If Cells(i, 2) > 50 Then
counter = counter + 1
Cells(i, 2).Font.ColorIndex = 5
Else
‘do nothing
Cells(i, 2).Font.ColorIndex = 3
End If
Next
Cells(21, 2) = counter
Cells(22, 2) = 20 – counter

No comments:

Post a Comment

Over 50 Ebooks Excel and VBA free Download

1. Statistics and Probability for Engineering Applications With Microsoft Excel by W.J. DeCoursey - PDF Free Download Download Siz...