我如何在VBA中使用ADODB连接

问题描述

  1. 我需要按数组排列数据
  2. 目标文件在网络上,并且在10秒内增加了数据值
  3. 需要连接到此文件.xls)并制作实时图表

现在的问题是如何使用ADODB来打开文件

发生2种情况:

第一:

dim path as string,DB as string
dim cnt as ADODB.Connection
OLEDB = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & path & DB & "; 
extended properties=""excel 12.0 xmlHDR=YES"";"
Set cnt = New ADODB.Connection
cnt.Open OLEDB

然后我收到“无法找到ISAM安装”错误

第二:

dim path as string,DB as string
dim cnt as ADODB.Connection
OLEDB = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & path & DB &"; 
extended properties=""excel 8.0;HDR=YES;IMEX=1;';"""
Set cnt = New ADODB.Connection
cnt.Open OLEDB

然后我得到了3706 runtime error,cant find supporter

那我怎么了?

解决方法

这是我通常使其运行的方式:

DbConn.Open "Provider=Microsoft.ACE.OLEDB.12.0;" & _
            "Data Source=" & path & ";" & _
            "Extended Properties=""Excel 12.0; HDR=YES"";"

其中path是完整的文件路径+文件名。 您可以找到有关连接字符串here

的更多信息

工作表名称和范围,然后输入SQL语句。例如:

sqlWhere = sheetName & "$A1:$Z1000"
DbRecSet.Open "SELECT * FROM [" & sqlWhere & "]",DbConn,adOpenStatic

编辑:

如果我正确理解你, 您有一个单元格,该单元格每10秒更改一次值,并且您想通过ADODB获得该值。

首先,在这种情况下,您可以从连接字符串中删除HDR=YES

假设单元格为A1

sqlWhere = sheetName & "$A1"
DbRecSet.Open "SELECT * FROM [" & sqlWhere & "]",adOpenStatic
returnValue = DbRecSet.Fields(0)
,

path = test_fdr&“”&today_total&“ .xls”

 OLEDB = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source= " & path & 
 ";Extended Properties=""Excel 8.0;HDR=YES"";"

  Set cnt = New ADODB.Connection
  cnt.Open OLEDB

  Rcdset.Open Source:="[" & TestSheetName & "$]",_
  ActiveConnection:=cnt,_
  CursorType:=adOpenStatic,_
  LockType:=adLockReadOnly,_
  Options:=adCmdTable

  With Sheets(3).QueryTables.Add(Connection:=Rcdset,Destination:=Target_rng)