我一直在寻找使用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
答案 0 :(得分:-2)
您可以使用adodb对象。
This video is a good tutorial for this.
以下是如何使用adodb的示例。您需要为此安装activeX Data Objects Libary。
对于.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