[英]Excel VBA run query from SMS Access database
I tried to run a query from an Excel worksheet. 我试图从Excel工作表中运行查询。 Below is my code but I think I am missing something here it does not work.
下面是我的代码,但是我想我在这里找不到东西。 I think my problem is the SQL code.
我认为我的问题是SQL代码。 Any help?
有什么帮助吗?
Thanks 谢谢
Baha 巴哈
Option Explicit
Const TARGET_DB1 = "DB_PlayerMasterManual.mdb"
Const CopyTarget_DB1 = "DB_PlayerMasterManualBackUp.mdb"
Sub DisplayRatings1()
Dim cnn As ADODB.Connection
Dim rst As ADODB.Recordset
Dim fld As ADODB.Field
Dim MyConn
Dim i As Long
Dim lastrow As Long
Dim cel As Range
lastrow = Sheets("RatingReport").Range("A1048576").End(xlUp).Row
Dim ShDest As Worksheet
Set ShDest = Sheets("RatingReport")
Set cnn = New ADODB.Connection
MyConn = "J:\Gaming Common\PlayerMaster_Manual" & "\" & _
"DataFiles\" & TARGET_DB1
With cnn
.Provider = "Microsoft.Jet.OLEDB.4.0"
.Open MyConn
End With
Set rst = New ADODB.Recordset
rst.CursorLocation = adUseServer
rst.Open "Select CustName & _
FROM tblRating WHERE CustID='" & _
CustIdTB.Value & "' ", cnn, , , adCmdTable
ShDest.Activate
Range("A1").CurrentRegion.Offset(1, 0).Clear
i = 0
With Range("A1")
For Each fld In rst.Fields
.Offset(0, i).Value = fld.Name
i = i + 1
Next fld
End With
Range("A2").CopyFromRecordset rst
rst.Close
cnn.Close
End Sub
You don't seem to be defining TARGET_DB1
anywhere. 您似乎在任何地方都没有定义
TARGET_DB1
。 I guess it's the filename of the database. 我想这是数据库的文件名。 Perhaps that's deliberate or it might be a mistake.
也许这是故意的,或者可能是一个错误。 If a mistake, correct that.
如果有错误,请更正。 Assuming that's a Global or a Function you also have a slight issue with the building of your query over 3 lines:
假设这是一个全局或函数,那么在3行以上的查询中,您也会遇到一个小问题:
Try changing: 尝试更改:
rst.Open "Select CustName & _
FROM tblRating WHERE CustID='" & _
CustIdTB.Value & "' ", cnn, , , adCmdTable
to: 至:
rst.Open "Select CustName " & _
"FROM tblRating WHERE CustID='" & _
CustIdTB.Value & "' ", cnn, , , adCmdTable
UDPATE: UDPATE:
As per comment, try: 根据评论,尝试:
rst.Open " (Select CustName " & _
"FROM tblRating WHERE CustID='" & _
CustIdTB.Value & "') ", cnn, , , adCmdTable
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.