【问题标题】:How can I "copy" a query from a microsoft access database into an excel spreadsheet using microsoft vba?如何使用microsoft vba将查询从microsoft access数据库“复制”到excel电子表格中?
【发布时间】: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 电子表格?

标签: vba excel ms-access


【解决方案1】:

这是抓取整个表格的类似内容,我没有引入它们已经存在的字段名称。当您执行此操作时,不要忘记 ID 将与表字段数据一起提供。

Private Sub getDataTable_Click()
    Dim conn As Object ' connection
    Dim rs As Object 'record set
    Dim strSql As String
    Dim strConnection As String
    Dim placementRange As Range

'如果您想在复制前清除,请为您的工作表和范围更新此内容

Worksheets("mtrInteraction").Range("I2:P25").ClearContents

    Set conn = CreateObject("ADODB.Connection")

    'update this for the workbook,worksheet, and range where you want it

'为表格和你想要桌子的范围更新这个,左上角

Set placementRange = Worksheets("mtrInteraction").Range("I2")

'更新您的路径和数据库名称

'Build your connection and path
strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
    "Data Source=C:\yourpath\yourpath\updatethis.accdb"

'为您的查询更新此内容,您只需更改表名即可复制整个表,在上面的连接中指定了数据库名称

'让你的 sql 查询从你的表名中全选

strSql = "SELECT * FROM tbl_MTR;"

    'open it you might want an error handler here
    conn.Open strConnection

    'get the recordset
    Set rs = conn.Execute(strSql)

    'copy your recordset in
    placementRange.CopyFromRecordset rs

    rs.Close
    Set rs = Nothing
    conn.Close
    Set conn = Nothing

End Sub

以下是存根中的相同内容,其中包含您想要的字段名称和用于特定定位的单元格中的数据值:

Private Sub CommandButton1_Click()
Dim inputSheet As Worksheet
Dim fieldSTR As String
Dim placementRange As Range

Dim rs As Object 'record set

Dim conn As Object
Dim strQuery As String

Dim myDB As String

Set inputSheet = ThisWorkbook.Worksheets("Sheet1")
Set placementRange = inputSheet.Range("E2")

fieldSTR = CStr(inputSheet.Cells(3, 3).Value) 'C3 cell
myDB = "C:\yourpath\yourpath\updatethis.accdb"

Set conn = CreateObject("ADODB.Connection")

    With conn
        .Provider = "Microsoft.ACE.OLEDB.12.0"    'For *.ACCDB Databases
        .ConnectionString = myDB
        .Open
    End With


strQuery = "SELECT * FROM " & _
            "tbl_test WHERE Color = " & "'" & fieldSTR & "'" & ";"

'The below gives the same result as * but you could limit the fields returned as well
'tbl_test.ID, tbl_test.Color, tbl_test.number

MsgBox (strQuery)

Set rs = conn.Execute(strQuery)

placementRange.CopyFromRecordset rs

rs.Close
Set rs = Nothing
conn.Close
Set conn = Nothing

End Sub

【讨论】:

  • 你能给我解释一下这行“Worksheets("mtrInteraction").Range("I2:P25").ClearContents" 和这行“Set placementRange = Worksheets("mtrInteraction").Range ("I2")" 做什么?我基本上只是将您的代码用作模板,同时插入我需要更改的内容,并且我认为查询中的数据不会进入电子表格。
  • 确保放置范围是我希望将表格复制到工作表“mtrInteraction”的位置,您将拥有不同的工作表名称,并且可能希望表格的左上角位于其他位置,更改它因此。清除只是为了事先清除该区域,您可能需要更大的范围。所以我清除范围,然后复制到该范围。这就对了。清除并复制记录集。
  • 我为你的答案添加了一些 cmets。您必须更新路径、工作表名称、表格名称和放置范围,您不必在复制前清除但如果数据大小不同怎么办?您需要先清除 a 范围。
  • 我已经完成了所有我相信的事情,比如说我的 excel 表现在是空白的,所以清晰的内容基本上什么都不做,对吗?放置范围仍然是我有点困惑的地方,为什么它只是通过一个单元格而不是一个范围(范围(“I2”))?这只是说您希望放置表格左上角的位置吗?如果有帮助,我会重新发布我的代码,而是更新。
  • 如果是空白纸,则无需清除。只需用 ' 注释掉该行,它就不会被使用。是的,它只指定副本的左上角锚单元格。为什么?这有助于避免复制粘贴时范围大小不匹配,如果您指定范围并且它们的大小不同,则会出现下标错误,如果它们是您范围内的数据,则可能会出现错误,这基本上可以防止一堆错误。
【解决方案2】:

这段代码对我有用,它被剥离了,所以它可能无法干净地编译:

Sub LoadRecordset(Sheet1 As Worksheet, query As String)
    Dim cnpubs As ADODB.Connection
    Dim rsPubs As ADODB.Recordset

    Set cnpubs = New ADODB.Connection
    cnpubs.ConnectionString = "Driver={SQL Server};Server=TESTDS;Database=TEST1;UID=sa;PWD=WERQEWDS"
    cnpubs.Open

    Set rsPubs = New ADODB.Recordset

    With rsPubs
        .ActiveConnection = cnpubs
        .Open query
        fldCount = .Fields.Count
        iRow = 1
        Sheet1.Rows(iRow & ":" & Rows.Count).Delete
        For iCol = 0 To fldCount - 1
            Sheet1.Cells(iRow, iCol + 1).Value = .Fields(iCol).Name
        Next
        iRow = iRow + 1
        Sheet1.Range("A" & iRow).CopyFromRecordset rsPubs
        .Close
    End With
    cnpubs.Close
    Set rsPubs = Nothing
    Set cnpubs = Nothing

   Sheet1.Cells.EntireColumn.AutoFit
End Sub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-07
    • 1970-01-01
    • 1970-01-01
    • 2010-11-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多