CÔNG TY CỔ PHẦN BLUESOFTS

CÔNG TY CỔ PHẦN BLUESOFTS

Lập trình VBA Liên kết dữ liệu từ website vào Excel với QueryTable



Hướng dẫn lập trình VBA để lấy dữ liệu từ website vào Excel với đối tượng QueryTable. Dữ liệu lấy dạng table có ID

(*) Mã nguồn:
'-------CODE--------
Option Explicit
'Author: Nguyen Duy Tuan - http://bluesofts.net
Sub LayTableTuWeb() 
   Dim qry As QueryTable 
   Dim sh As Worksheet 
   Dim CnnStr As String 
   Set sh = ThisWorkbook.Sheets("Webtable") 
   'Xoa querytable truoc do
   XoaQT sh 
   CnnStr = "URL;https://s.cafef.vn/Lich-su-giao-dich-VCB-6.chn" 
   Set qry = sh.QueryTables.Add(CnnStr, sh.Range("A5")) 
   'Query
   qry.WebSelectionType = xlSpecifiedTables 
   qry.WebFormatting = xlWebFormattingNone 
   qry.WebTables = """tblStats"",""tblData"""  'Tat ca cac table
   qry.Refresh  'Load du lieu
End Sub 
 Sub XoaQT(sh As Worksheet) 
   Dim qry As QueryTable 
   On Error Resume Next  'Bo qua loi
   For Each qry In sh.QueryTables 
      qry.ResultRange.ClearContents  'Xoa data trong vung table
      qry.Delete  'Xoa QueryTable
   Next 
End Sub
 
'------END COPY-------
Video hướng dẫn chi tiết: