vba ado怎么逐条导出记录
2个回答
展开全部
试试下面的代码,用ado读取数据:
在如下实例中,对红字部分如何修改,比如保存数据到:sheet(1)的f列30行起
Private Sub data_copy()
Dim lcConnectionString, lcCommandText As String '定义两个字符串,用来输入命令参数
Dim loADODBConnection As ADODB.Connection '定义一个ADO的Connection对象变量
Dim loADODBRecordset As ADODB.Recordset '定义一个ADO的Recordset对象变量
'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
'赋值给lcConnectionString,用于创建连接字符串
lcConnectionString = "Driver={Microsoft Excel Driver (*.xls)}; " & _
"DBQ=" + ActiveWorkbook.FullName + ";" & _
"ReadOnly=True"
'输入SQL查询语句,用来实现数据库的查询
lcCommandText = "select * from [sheet1$] "
'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
'创建对象
Set loADODBConnection = CreateObject("ADODB.Connection")
Set loADODBRecordset = CreateObject("ADODB.Recordset")
'打开对象
loADODBConnection.Open lcConnectionString '根据连接字符串打开连接
loADODBRecordset.Open lcCommandText, loADODBConnection, 3, 1, 1 '根据SQL查询语句,查询数据库
'~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
'添加新的工作表,将数据复制到新工作表中
' Sheets.Add
'定义单元格变量
Dim r, f As Integer
r = 15 '定义查询结果的起始行
'复制字段名
For f = 0 To loADODBRecordset.Fields.Count - 1
Sheets(1).Cells(r, f + 1) = loADODBRecordset.Fields(f).Name
Next
'逐条复制字段值
While Not loADODBRecordset.EOF
r = r + 1
For f = 0 To loADODBRecordset.Fields.Count - 1
Sheets(1).Cells(r, f + 1) = loADODBRecordset.Fields(f).Value
Next
'记录指针后移
loADODBRecordset.MoveNext
Wend
'关闭连接
loADODBConnection.Close
End Sub
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询