excel宏来执行多个查询和获取记录

问题描述 投票:0回答:2

截至目前,我只有一个标准的数据库连接(通过菜单或工具栏)工作正常。但是我想获取三个不同时期的记录(每个表可以有不同的查询)。在定位之前我做了各种尝试,但我无法通过宏获取任何记录。我正在寻找实施我的要求的建议或方向。

单元格A1 =“名称”。

for,sheet1:从testDB中选择“name”

for,sheet2:从testDB中选择“name”,其中data> = abc&date <= xyz

for,sheet3:从testDB中选择“name”wehre data> = xyx

excel excel-vba vba
2个回答
0
投票

使用“开发工具”选项卡中的“记录宏”按钮记录在使用所需参数创建此类连接时所执行的所有操作。

然后停止录制并转到VBA屏幕,查看代码的外观,并将其更改为您喜欢的位置或以这种方式记录所有三个版本。

现在将这些VBA代码集成到您的VBA脚本中。


0
投票

尝试使用ADODB在代码中完成所有操作。

首先,在每个工作表上,在单元格A1(可能)中创建一个名为的新命名范围:

“查询”和xsheet.name

在该单元格中,将查询特定于该工作表

然后在VBA代码模块中使用此代码:

sub getData()

dim cn as new adodb.connection
dim rs as new adodb.recordset

dim connStr as string ' connection string
dim sUDLFile as string ' path and name of Microsoft Data Link File (UDL FILE)
dim xSheet as worksheet

connStr="File Name=" & sUDLFile

cn.open connstr

'loop through all the worksheets
for each xSheet in thisworkbook.worksheets

    with rs
        ' open the connection to the db...
        .activeconnection=cn

        'get the query from the range on the worksheet!
        sQry=xsheet.range("Query" & xsheet.name).text

        ' open the query from the DB
        .open sQry

        ' dump the dataset onto the worksheet with one line of code in B5 cell!
        xsheet.range(B5).copyfromrecordset rs
        .close
    end with
next

' clean up and release memory
cn.close
set cn=nothing
set rs=nothing
'
end sub

在MS Windows资源管理器中创建连接字符串(UDL FILE):

  1. 导航到工作簿所在的目录
  2. 右键单击并选择New ...> Microsoft Data Link。
  3. 将名称更改为一个好名称(也许是name.udl)
  4. 双击新文件并设置设置以创建并测试与db的连接

有问题,请问!

菲利普

© www.soinside.com 2019 - 2024. All rights reserved.