【发布时间】:2015-04-04 11:59:49
【问题描述】:
我在 Visual Studio Express 中使用 VBA。我想要做的是给出我通过VB导出MS Access DB创建的excel电子表格的第一行,列名,即我在我的DB中的名称。
有 10 列第 9 列被跳过,我还将电子表格隔开以允许第一行有标题,我将如何用我的数据库的列名填充电子表格的第一行? 也可以直接通过代码分配名称,而不是从数据库中传递列标题。
我的代码:
Public Sub ExportEx()
Dim strSQL_Query As String
Dim oCN As ADODB.Connection
Dim oCMD As ADODB.Command
Dim oRecords As ADODB.Recordset
Dim strDBPath As String
Dim varValues As Object
Dim lngRows As Long
Dim lngCols As Long
Dim strCN As String
strDBPath = Application.StartupPath & "\SCO_Leaderboard.accdb"
strCN = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strDBPath & ";" & _
"Persist Security Info=False;"
strSQL_Query = "Select top 10 Rank, Username, Time_Played, Lv, EXP, Floor, Col, Logins, Status FROM tblUsers ORDER BY Rank ASC"
Dim oExcel As Object
Dim oBook As Object
Dim oSheet As Object
oExcel = CreateObject("Excel.Application")
oBook = oExcel.Workbooks.Add
oSheet = oBook.Worksheets(1)
oCN = New ADODB.Connection
oCN.ConnectionString = strCN
oCN.Open()
oCMD = New ADODB.Command
oCMD.ActiveConnection = oCN
oCMD.CommandText = strSQL_Query
oRecords = oCMD.Execute
varValues = oRecords.GetRows
lngCols = UBound(varValues, 2)
lngRows = UBound(varValues, 1)
oSheet.Range("A2", oSheet.Range("A2").Offset(lngRows, lngCols)) = varValues
oBook.SaveAs(Application.StartupPath & "\Top_10_All_Time.xls")
oExcel.Quit()
MsgBox("An Excel spreadsheet has been created under:" & vbNewLine & vbNewLine & Application.StartupPath & "\Top_10_All_Time.xls")
'' Clean up...
oCMD = Nothing
oCN.Close()
oCN = Nothing
另一方面,我将如何在 Excel 中将字段隔开,以便所有数据都适合列?
感谢您的帮助,
安迪
【问题讨论】:
标签: vba excel ms-access export-to-excel