Biến mảng(array) trong VBA

Cách lập trình biến mảng(array) trong VBA

Cú pháp khai báo biến mảng:
Dim TenBien(Chỉ số đầu To Chỉ số cuối) as Kiểu
Một số hàm liên quan mảng:
 Lbound lấy chỉ số đầu tiên của mảng
 Ubound lấy chỉ số cuối của mảng
 Join : nối các phần tử màng thành chuổi
 Slipt: chia 1 chuổi thành 1 mảng

Câu hỏi:
1.    Biến bình thường và biến mảng khác nhau như thế nào ?
2.    Ứng dụng biến mảng trong phát triển phần mềm như thế nào ?
Sau khi làm các ví dụ ta sẽ trả lời được 2 câu hỏi trên ?
 

Ví dụ 1: khởi tạo biến mảng có tên là a
 Dim a(0 To 3) As Integer
   a(0) = 6  
   a(1) = 2
   a(2) = 4
   a(3) = 6

? Biến trên có bao nhiêu phần tử
? In giá trị phần tử thứ 2 ra màn hình

 

Ví dụ chèn dữ liệu vào table từ file data.txt

Có dữ liệu như sau:

 

TT Ten Lop Diem
1 Tran A Lop 6 8
2 Tran B Lop 6 9

Private Sub Command0_Click()
    DoCmd.SetWarnings False
    a = ReadTextFile("D:\data.txt")
    Dim strLineArray As Variant
    strLineArray = Split(a, vbCrLf)
    SQL = "Insert into tbText(TT,HOTEN,LOP,DIEM) Values('{0}','{1}','{2}',{3})"
    For i = 1 To UBound(strLineArray)
         str_get_row = strLineArray(i)
         strCellArray = Split(str_get_row, vbTab)
         
         sql_temp = SQL
         
         For j = 0 To UBound(strCellArray)
                sql_temp = Replace(sql_temp, "{" & j & "}", strCellArray(j))
         Next
         DoCmd.RunSQL sql_temp
         'MsgBox sql_temp
         
    Next
      DoCmd.SetWarnings True
End Sub

Public Function ReadTextFile(psPathFile As String) As String
   Dim iFile As Integer _
      , sFileContents As String
   iFile = FreeFile
   Open psPathFile For Input As iFile
   sFileContents = Input(LOF(iFile), iFile)
   Close iFile
   ReadTextFile = sFileContents
End Function