在Excel中不能直接使用SQL语句,要使用的话,必须使用VBA来实现,并且,还要先创建一个连接,如下是范例,希望对你有所帮助。
'''先创建连接
Dim cnn As ADODB.Connection
Dim sCnn As String
Dim sDB As String
Dim sPath As String
sPath = ActiveWorkbook.Path
If Right(sPath, 1) = "\" Then sPath = Left(sPath, Len(sPath) - 1)
sDB = sPath & "\MyDb.mdb"
'''可以使用如下的两种方式来连接
If 1 Then
'对于Jet OLEDB,也就是MDB格式的数据库
sCnn = ""
sCnn = sCnn & ";Provider = Microsoft.Jet.OLEDB.4.0"
sCnn = sCnn & ";Data Source = " & Chr$(34) & sDB & Chr$(34)
sCnn = sCnn & ";User ID = 这里是用户名"
sCnn = sCnn & ";Jet OLEDB:Database PassWord = 这里是密码" '如果有密码的话
Else
'对于ODBC(要在系统中指定数据源和驱动程序)
sCnn = ""
sCnn = sCnn & ";Driver = {Microsoft Access Driver (*.mdb)}" '可以是其它的驱动
sCnn = sCnn & ";DefaultDir = " & sPath & "\"
sCnn = sCnn & ";DBQ = " & Chr$(34) & sDB & Chr$(34)
sCnn = sCnn & ";UID = 用户名"
sCnn = sCnn & ";PWD = 密码"
End If
Set cnn = New ADODB.Connection
With cnn
.CursorLocation = adUseClient
.ConnectionTimeout =9
.Open sCnn
.Close
End With