【问题标题】:Export from Access to Excel to an existing worksheet从 Access 导出到 Excel 到现有工作表
【发布时间】:2020-07-13 22:05:55
【问题描述】:

示例: 我有 excel 文件 test.xls,其中有 sheet1、sheet2、sheet3、sheet4 和一些信息。 我想将 4 个查询的结果导出到这些工作表,但我想在最后一行数据之后添加结果,而不是覆盖它。

【问题讨论】:

  • 为什么... VBA 被认为是理所当然的 ;) ?

标签: ms-access vba


【解决方案1】:

我最近也在做类似的事情。在 Excel 中,我使用了 VBA。

Dim cn As Object
Dim rs As Object
Dim strFile As String
Dim strCon As String
Dim strSQL As String
Dim s As String
Dim i As Integer, j As Integer
Dim StartDate As Date, EndDate As Date, ModStartDate As Date, ModEndDate As Date


'Modify the Start date because Maint 24hr cycle is 930 - 930 not 12 - 12
ModStartDate = StartDate - 1


''Access database
strFile = "S:\IT\Databases\Main_BE.mdb"

''This is the Jet 4 connection string, you can get more
''here : http://www.connectionstrings.com/excel
strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strFile & ";"

''Late binding, so no reference is needed
Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
cn.Open strCon


'Get the info from Access
strSQL = "SELECT * FROM Work_Orders " _
    & "WHERE Repair_Start_Date >= #" & ModStartDate & "# " _
    & "AND Repair_Start_Date <= #" & EndDate & "# " _
    & "ORDER BY Repair_Start_Date, Repair_Start_Time"
rs.Open strSQL, cn

'Paste the SQL query at A10 Sheet3
Sheet3.Cells(10, 1).CopyFromRecordset rs

''Tidy up
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing

您只需要修改 SQL 语句,然后添加一个新行,您可以使用一个变量来计算现有行数:

"=Counta(some range:some range)"

然后将 1 加到下一行的变量中。

【讨论】:

    【解决方案2】:

    谢谢大家! 我可以使用:

        Private Sub Command0_Click()
    Dim rstName As Recordset
    Set rstName = CurrentDb.OpenRecordset("query1")
    
    Dim objApp As Object, objMyWorkbook As Object, objMySheet As Object, objMyRange As   Object
    
    Set objApp = CreateObject("Excel.Application")
    Set objMyWorkbook = objApp.Workbooks.Open("c:/exportarexcell/teste.xls")
    Set objMySheet = objMyWorkbook.Worksheets("FolhaTeste")
    Set objMyRange = objMySheet.Cells(objApp.ActiveSheet.UsedRange.Rows.Count + 1, 1)
    
    With objMyRange
     rstName.MoveFirst 'Rewind to the first record
     .Clear
     .CopyFromRecordset rstName
    End With
    End Sub
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-04
      • 1970-01-01
      • 2014-10-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多