- Tham gia
- 18/3/08
- Bài viết
- 8,310
- Được thích
- 15,867
- Giới tính
- Nam
- Nghề nghiệp
- Làm ruộng.
Thông thường ta truy vấn dữ liệu bằng ADO trên cùng file thì ta vẫn phải mở kết nối đến chính file thực thi đó. Điều này làm giảm đi tốc độ khi chạy code.
Hôm nay mình xin chia sẻ với các bạn cách truy vấn dữ liệu mà không cần mở kết nối trên cùng file thực thi.
Hôm nay mình xin chia sẻ với các bạn cách truy vấn dữ liệu mà không cần mở kết nối trên cùng file thực thi.
Mã:
Sub LocDL_HLMT()
Dim rst As Object, vArray As Variant, i As Long, thoigian As Long 'Khai bao bien
Set rst = CreateObject("ADODB.Recordset") ' Khoi tao Recordset
vArray = Sheet1.Range("A2:D10001").Value ' Du lieu nguon vao mang
thoigian = Timer()
With rst
'Khai bao va mo Recorset
.Fields.Append "ID", 3
.Fields.Append "MatID", 200, 10
.Fields.Append "Balance", 3
.Open
'Dua du lieu nguon tu mang da set vao Recordset
For i = LBound(vArray) To UBound(vArray)
.AddNew
.Fields("ID").Value = vArray(i, LBound(vArray))
.Fields("MatID").Value = vArray(i, LBound(vArray) + 1)
.Fields("Balance").Value = vArray(i, LBound(vArray) + 3)
.Update
Next
'Loc du lieu trong Recordset
.Filter = "Balance " & Sheet2.Range("B1")
End With
Sheet2.Range("A2:D11000").ClearContents 'Xoa vung du lieu
Sheet2.Range("A4").CopyFromRecordset rst 'Do du lieu tu Recordset da loc xuong sheet
MsgBox Timer - thoigian
rst.Close
Set rst = Nothing
End Sub