Câu lệnh FOR NEXT

Một phần của tài liệu microsoft excel (Trang 42 - 45)

Mục đích: Thực hiện vòng lặp biết trước số lần lặp Cú pháp :

FOR <Counter>= <Start> TO <End> STEP <n> //Câu lệnh

NEXT <Counter> Mô tả:

Ban đầu <Counter> được gán giá trị <Start> //Câu lệnh được thực hiện

Sau đó <Counter> được tăng lên <n> //Câu lệnh được thực hiện

Việc này lặp lại cho đến khi <Counter> nhận giá trị <End>

Ví dụ: S= 0 FOR i= 1 To 100 STEP 2 S= S+i NEXT i Trong ví dụ này sẽ tính tổng của các số lẻ từ 1 đến 99

*) Chú ý: Trong trường hợp STEP là 1 thì ta không cần thêm vào câu lệnh VD: Tính tổng 100 sốđầu tiên S= 0 FOR i= 1 TO 100 S= S+i NEXT i Chương trình ví d: Viết hàm tính tổng các số trong một vùng nào đó Function h_SUM(m_Area As Range) As Double

Dim i As Integer, j As Integer h_SUM = 0

For i = 0 To m_Area.Rows.Count - 1 For j = 0 To m_Area.Columns.Count - 1

If Cells(m_Area.Row + i, m_Area.Column + j).Font.ColorIndex = 3 Then h_SUM = h_SUM + Cells(m_Area.Row + i, m_Area.Column + j).Value End If

Next i

End Function

Function tax_SUM(m_Area As Range) As Double Dim i As Integer, j As Integer

tax_SUM = 0

For i = 0 To m_Area.Rows.Count - 1 For j = 0 To m_Area.Columns.Count - 1

Select Case Cells(m_Area.Row + i, m_Area.Column + j).Font.ColorIndex Case 3

tax_SUM = tax_SUM + Cells(m_Area.Row + i, m_Area.Column + j).Value * 0.1 Case 5

tax_SUM = tax_SUM + Cells(m_Area.Row + i, m_Area.Column + j).Value * 0.05 End Select

Next j Next i

End Function

Function Con_SUM(m_Area As Range, n_Area As Range) As Double Dim i As Integer, j As Integer

Con_SUM = 0

For i = 0 To m_Area.Rows.Count - 1 For j = 0 To m_Area.Columns.Count - 1

Select Case Cells(m_Area.Row + i, m_Area.Column + j).Font.ColorIndex Case Cells(n_Area.Row, n_Area.Column).Font.ColorIndex

Con_SUM = Con_SUM + Cells(m_Area.Row + i, m_Area.Column + j).Value * Cells(n_Area.Row, n_Area.Column + 1).Value

Case Cells(n_Area.Row + 1, n_Area.Column).Font.ColorIndex

Con_SUM = Con_SUM + Cells(m_Area.Row + i, m_Area.Column + j).Value * Cells(n_Area.Row + 1, n_Area.Column + 1).Value

Case Else

Con_SUM = Con_SUM + Cells(m_Area.Row + i, m_Area.Column + j).Value * 0 End Select

Next j Next i

End Function

Function Text_SUM(m_Area As Range, n_Area As Range) As Double Dim i As Integer, j As Integer

Text_SUM = 0

For i = 0 To m_Area.Rows.Count - 1 For j = 0 To m_Area.Columns.Count - 1

If IsNumeric(Cells(m_Area.Row + i, m_Area.Column + j).Value) Then Select Case Cells(m_Area.Row + i, m_Area.Column + j).Font.ColorIndex Case Cells(n_Area.Row, n_Area.Column).Font.ColorIndex

Text_SUM = Text_SUM + Cells(m_Area.Row + i, m_Area.Column + j).Value * Cells(n_Area.Row, n_Area.Column + 1).Value

Text_SUM = Text_SUM + Cells(m_Area.Row + i, m_Area.Column + j).Value * Cells(n_Area.Row + 1, n_Area.Column + 1).Value

Case Else

Text_SUM = Text_SUM + Cells(m_Area.Row + i, m_Area.Column + j).Value * 0 End Select End If Next j Next i End Function

Một phần của tài liệu microsoft excel (Trang 42 - 45)