【问题标题】:Creating a New Excel Spreadsheet from a Dynamic Listbox in an MS Access Form从 MS Access 表单中的动态列表框创建新的 Excel 电子表格
【发布时间】:2016-04-21 17:20:18
【问题描述】:

我有一个基于 MS Access 表单的搜索引擎。该表单使用 ListBox ("List1") 来显示基于关键字搜索的结果。我想创建一个按钮(“Command47”),它将在新的 Excel 电子表格中显示列表框的结果。我不想将文件保存到文件路径,只想打开它。以下是我目前拥有的:

Private Sub Command47_Click()

      Dim qdef As DAO.QueryDef

      Set qdef = CurrentDb.CreateQueryDef("VFE")

      qdef.SQL = Me.List1.RowSource

      qdef.Close

      Set qdef = Nothing

      CurrentDb.QueryDefs.Delete "VFE"

End Sub

需要知道从这里去哪里。

【问题讨论】:

    标签: sql vba ms-access listbox ms-access-2013


    【解决方案1】:

    基本上,您需要做的是打开一个 Excel 实例,创建一个工作簿对象,然后用记录集填充它。

    为了使其工作,您必须添加对 Microsoft Excel 版本号 对象库

    的引用

    References window example

    Private Sub Command47_Click()
      Dim qd As DAO.QueryDef, rs As DAO.Recordset
      Dim xl As Excel.Application, wbk As Excel.Workbook, wsh As Excel.Worksheet
      Dim i As Long
      Set qd = CurrentDb.CreateQueryDef("VFE")
      qd.SQL = Me.List1.RowSource
      Set rs = qd.OpenRecordset(dbOpenSnapshot)
    
      Set xl = New Excel.Application
      xl.visible = False
      Set wbk = xl.Workbooks.Add(1)   ' Creates a new workbook with 1 worksheet
      Set wsh = wbk.Worksheets(1)     ' Selects the first worksheet
      With wsh
        .Name = left(qd.Name, 32)
        .Range("A1").Value = qd.Name
        For i = 1 To rs.Fields.Count  ' Populates the 2nd row with field names
          With .cells(2, i)
            .Value = rs.Fields(i - 1).Name
            .font.bold = True
          End With
        Next
        .Range("A3").CopyFromRecordset rs
      End With
      xl.visible = True
      qd.close
      CurrentDB.QueryDefs.Delete("VFE")
    End Sub
    

    希望对你有帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-24
      • 1970-01-01
      • 2013-06-21
      • 1970-01-01
      • 2014-10-13
      • 1970-01-01
      相关资源
      最近更新 更多