【问题标题】:VB6 insert data into excel from databaseVB6将数据从数据库插入到excel中
【发布时间】:2018-02-22 19:52:30
【问题描述】:

我一直在寻找使用 vb6 代码和访问数据库将数据插入 excel 的解决方案。在很多情况下,我需要使用不同的数据记录多次写入 Excel 电子表格。我有一个现有的工作簿,我正在尝试打开并在完成后“另存为”。我已经能够打开 excel 工作簿,访问我正在写入的工作表以及我正在写入的单元格,但是我只能写入工作簿一次,当我离开打开的工作簿的范围时,连接关闭。

我有一个创建工作簿对象的子例程,打开现有工作簿和工作表,写入指定的单元格编号以插入新数据。我查看了official support pages,目前似乎没有我想要的东西。

是我把这弄得太复杂了还是有解决办法?请帮忙。

我当前的代码:

行数组

Private oldDataRowArray(3 To 21) As Integer
Private updatedDataRowArray(5 To 2) As Integer

循环逻辑

Dim i As Integer
Dim n As Integer
i = 3
n = 5
Do While i <= UBound(oldDataRowArray) And n <= UBound(updatedDataRowArray)
EditExcelSheet txtWorkbookFileName.Text, i, n //sub routine
i = i + 3 //skip number of cells
n = n + 3 //skip number of cells
Loop

将数据插入 Excel 的子程序

Private Sub EditStakingSheet(ByVal workbook As String, ByVal oldDataRowIndex As Integer, ByVal newDataRowIndex As Integer)
Dim objExcel As Object
Dim objWorkBook As Object
Dim objSheet As Object

Set objExcel = New Excel.Application
Set objWorkBook = objExcel.Workbooks.Open(workbook)
Set objSheet = objWorkBook.Worksheets(1)

objExcel.Visible = True
//insert old value
objSheet.Cells(oldDataRowIndex , 26).Value = "old Value"

//insert new value
objSheet.Cells(newDataRowIndex , 26).Value = "new Value"

End Sub

【问题讨论】:

  • 我不确定你的意思是什么:“到目前为止,我已经能够打开 excel 工作簿,定位工作表和我正在写入的单元格,但是我只能写入工作簿一次,当我离开打开的工作簿的范围时,连接就消失了。”。您能否发布代码,因为您应该也可以使用 VB6 连接到 Access,然后将数据写入 Excel。

标签: excel ms-access vb6 ado


【解决方案1】:

你可以使用 adodb 对象。

This video is a good tutorial for this.

这是一个如何使用 adodb 的示例。您需要为此安装 activeX 数据对象库。 对于.source=,您可以使用任何 sql-query。

Public Function get_Value(table As String, order_by As String) As Variant

Set db_data = New ADODB.Recordset

Set db1 = New ADODB.Connection

pDB_path = "#enter db-path here"

db1.ConnectionString = _
    "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & pDB_path & ";Persist Security Info=False;"

db1.Open


With db_data
    .ActiveConnection = db1
    .Source = "SELECT * FROM " & table & " ORDER BY " & order_by & " ASC"
    .LockType = adLockReadOnly 'read only access to db
    .CursorType = adOpenStatic 'how to update the database
    .Open
End With

get_Value = TransposeArray(db_data.GetRows)

db_data.Close

End Function

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-08
    • 1970-01-01
    • 2019-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多