【发布时间】:2018-01-11 01:08:21
【问题描述】:
希望我问的问题很清楚,老实说,我对使用 Microsoft VBA 也很陌生(实际上是从今天开始尝试使用它)。我正在尝试从 Microsoft Access 数据库中“获取”一个查询/数据表,但我很难理解语法以及命令的确切作用。目前看来我正在进入查询,但只返回带有代码的数据表的第一个单元格:
Private Sub Select_From_Access()
Dim cn As Object
Dim rs As Object
Dim strSql As String
Dim strConnection As String
Dim placementRange As Range
'DescriptionErrorByLot is the worksheet I want to put the table in, the range A1:Z44 is what would hypothetically be cleared
'if it needed to be once there is data there and needs to be updated
Worksheets("DescriptionErrorByLot").Range("A1:Z44").ClearContents
Set cn = CreateObject("ADODB.Connection")
'This is where I want the query (table) to be placed?
Set placementRange = Worksheets("DescriptionErrorByLot").Range("A1")
'Connection string containing provider and file path to the database
strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=C:\Users\sjevne\Desktop\Database.accdb"
'Selecting the whole table from the query "jc_C2ComplaintCountbyLot10"? This is the queries name in the database
'To better explain what I'm talking about, there's buttons I can click on in the access database inside of the
'Reports section (click 'Reports' button) and then I click another button "Description errors by lot" and then
'A table/query with the name jc_C2ComplaintCountbyLot10 is open
strSql = "SELECT * FROM jc_C2ComplaintCountByLot10;"
cn.Open strConnection
Set rs = cn.Execute(strSql)
placementRange.CopyFromRecordset rs
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
End Sub
基本上我现在想知道的是,实际上是什么让我能够返回我感兴趣的数据表中的第一个单元格?显然,我怎样才能扩大范围以抓住整个东西? 任何帮助将非常感激!提前致谢。
编辑 1:代码
EDIT 2 :当我尝试将 SELECT * FROM 更改为我之前使用的现有连接到我想要的数据库查询时,我一直在玩代码,并且它说了一些关于多值单元格的内容,并且无法从不同的数据库中获取数据。 (此与工作表的连接以前用于创建自动表,因此当数据库表值发生更改时,电子表格会更改。我现在要做的只是使用宏“复制和粘贴”,因为以前的方法不是可悲的是,不再可用。
【问题讨论】:
-
如果我理解正确的话,名字都被打印出来了,但是唯一接收到值的单元格是 B2?
-
不完全,所以,“jc_C2ComplaintCountbyLot10”是数据库中的一个查询。它基本上只是一个大表,我可以手动复制和粘贴,但我可以节省制作宏的时间。当我现在按下我漂亮的小按钮时发生的事情是,它只会将表中的第一个单元格从数据库返回到我的 Excel 电子表格的 A1 中。
-
我同意马特的观点。
-
好吧,我删除了或者至少注释掉了很多我原来拥有的东西。基本上我为 sql 和连接路径创建了一个字符串,还尝试了 rs = cn.Execute(strSql) ,代码运行没有错误,但没有任何内容进入我的 excel 电子表格?