|
[广告] VBA代码宝 - VBA编程加强工具 · VBA代码随查随用 · 内置多项VBA编程加强工具 ★ 免费下载 ★ ★ 使用手册★
******************************
Excel中利用SQL语言连接外部数据-百度经验 https://jingyan.baidu.com/article/adc8151319a340b723bf7389.html
在【连接属性】对话框,切换到【定义】标签,在【命令文本】中输入如下语句:select * from [成绩表$],最后【确定】(此处命令文本中的代码是SQL的基本语句,虽然按照系统默认也可以获取外部数据,但此处是标准语法,方便后续对数据的进一步操作处理)
这样就能够在不打开外部数据源的情况下获取外部数据,而且当外部数据有更新时,我们只需要在此连接工作簿中右键【刷新】即可获得更新后的外部数据(不需要打开外部数据源)
****************************************************
在VBA中使用,SQL语言。
- Function SqlRetuRs(Str)
- Dim Cn As ADODB.Connection
- Set Cn = New ADODB.Connection
- Dim Rs As ADODB.Recordset
- Set Rs = New ADODB.Recordset
- Cn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Extended Properties='Excel 12.0;HDR=yes';data source=" & ThisWorkbook.fullName
- Rs.Open Str, Cn, adOpenKeyset, adLockOptimistic
- Set SqlRetuRs = Rs
- End Function
- Sub lll1()
- Dim Str, Rr
- Dim Sht As Worksheet
- Dim Rng As Range, oRng As Range
- Set Rng = Selection
- Set Rng = Rng.CurrentRegion
- Debug.Print Rng.Address
- Set Sht = Rng.Parent
- Rr = Rng.Row + Rng.Rows.Count + 20
- Set oRng = Sht.Range("A" & Rr - 5 & ":Z60000")
- oRng.Select
- oRng.Clear
- Set oRng = Sht.Range("A1:G" & Rr)
- oRng.Select
-
-
- Dim Rs As Recordset, Rs1 As Recordset, Rs2 As Recordset
-
- Str = "Select Distinct 地点 From [" & Sht.Name & "$" & oRng.Address(0, 0) & "] Where 地点 <> 'Null' "
- Set Rs = SqlRetuRs(Str)
-
- With Rs
- .MoveFirst
- For ii = 0 To .RecordCount - 1
- Str = "Select Sum(大小) From [" & Sht.Name & "$" & oRng.Address(0, 0) & "] Where 地点 = '" & .Fields(0) & "'"
- Set Rs1 = SqlRetuRs(Str)
- Str = "Select Count(地点) From [" & Sht.Name & "$" & oRng.Address(0, 0) & "] Where 地点 = '" & .Fields(0) & "'"
- Set Rs2 = SqlRetuRs(Str)
- ''
- Sht.Cells(Rr, 2) = Rs.Fields(0)
- Sht.Cells(Rr, 3) = Rs2.Fields(0)
- Sht.Cells(Rr, 4) = Rs1.Fields(0)
- Rr = Rr + 1
- .MoveNext
- Next ii
- End With
- End Sub
复制代码
**************************
|
|