【发布时间】:2016-08-30 21:38:06
【问题描述】:
由于这个特殊问题,我无法获取将导出数据从 Access 附加到 Excel 的代码。我创建了一个简单的 Access 数据库,其中一些数据显示在表单上。之后,可以使用代码将显示的记录导出到 Excel。
到目前为止一切顺利。但是,当我导出下一条记录时,它会覆盖 Excel 第一行中先前导出的数据。我希望代码附加到下一行等等。
我找到了一些关于如何附加“ActiveCell.Value”和“ActiveCell.Offset”的主题,但我的知识太有限,无法让它与代码一起使用。当我认为我得到它的那一刻,VBE 带有错误。好像搞不懂。
Private Sub Command15_Click()
Dim oExcel As Object
Dim oExcelWrkBk As Object
Dim oExcelWrSht As Object
Dim bExcelOpened As Boolean
'Start Excel
On Error Resume Next
Set oExcel = GetObject(, "Excel.Application") 'Bind to existing instance of Excel
If Err.Number <> 0 Then 'Could not get instance of Excel, so create a new one
Err.Clear
On Error GoTo Error_Handler
Set oExcel = CreateObject("excel.application")
bExcelOpened = False
Else 'Excel was already running
bExcelOpened = True
End If
On Error GoTo Error_Handler
oExcel.ScreenUpdating = False
oExcel.Visible = False 'Keep Excel hidden until we are done with our manipulation
'Set oExcelWrkBk = oExcel.Workbooks.Add() 'Start a new workbook
Set oExcelWrkBk = oExcel.Workbooks.Open("C:\test.xlsx") 'Open an existing Excel file
Set oExcelWrSht = oExcelWrkBk.Sheets(1) 'which worksheet to work with
'Start copying over your form values to the Excel Spreadsheet
'Cells(8, 3) = 8th row, 3rd column
oExcelWrSht.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0) = Me.1
oExcelWrSht.Cells(Rows.Count, 2).End(xlUp).Offset(1, 0) = Me.2
oExcelWrSht.Cells(Rows.Count, 3).End(xlUp).Offset(1, 0) = Me.3
oExcelWrSht.Cells(Rows.Count, 4).End(xlUp).Offset(1, 0) = Me.4
oExcelWrSht.Cells(Rows.Count, 5).End(xlUp).Offset(1, 0) = Me.5
oExcelWrSht.Cells(Rows.Count, 6).End(xlUp).Offset(1, 0) = Me.6
oExcelWrSht.Cells(Rows.Count, 7).End(xlUp).Offset(1, 0) = Me.7
oExcelWrSht.Cells(Rows.Count, 8).End(xlUp).Offset(1, 0) = Me.8
oExcelWrSht.Cells(Rows.Count, 9).End(xlUp).Offset(1, 0) = Me.9
'... and so on ...
oExcelWrSht.Range("A1").Select 'Return to the top of the page
' oExcelWrkBk.Close True, sFileName 'Save and close the generated workbook
' 'Close excel if is wasn't originally running
' If bExcelOpened = False Then
' oExcel.Quit
' End If Error_Handler_Exit:
On Error Resume Next
oExcel.Visible = True 'Make excel visible to the user
Set oExcelWrSht = Nothing
Set oExcelWrkBk = Nothing
oExcel.ScreenUpdating = True
Set oExcel = Nothing
Exit Sub Error_Handler:
MsgBox "The following error has occured" & vbCrLf & vbCrLf & _
"Error Number: " & Err.Number & vbCrLf & _
"Error Source: Export2XLS" & vbCrLf & _
"Error Description: " & Err.Description _
, vbOKOnly + vbCritical, "An Error has Occured!"
Resume Error_Handler_Exit End Sub
【问题讨论】:
-
如果您使用的是数据库,为什么要将记录附加到 Excel 中?为什么不将记录存储在 Access(这是数据库的用途)中并让 Excel 从数据库中提取所需的记录?
-
所以每次你运行它肯定会设置第 10 行的值?我错过了您尝试将其移至下一行的尝试?
-
@jkpieterse:我怎样才能做到这一点?你能把我推向正确的方向吗?
-
@Tim Edwards:抱歉,代码将导出的数据写入第 10 行。我尝试使用“ActiveCell.Value”和“ActiveCell.Offset”(未显示)来实现转到下一行在代码中),但每次我尝试时都会从 VBE 收到错误(我连续尝试了 3 天,但没有运气)。所以我又回到了代码工作的地方。
-
因此,要获取下一行,您需要使用
Cells(Rows.Count, 10).End(xlUp).Offset(1, 0) = "My Value"之类的内容,但将 10 更改为您想要的任何列。