我在Visual Studio Express中使用VBA。我想要做的是给出我通过VB,列名,即我在我的数据库中的名称导出MS Access DB创建的excel spreedsheet的第一行。VBA Excel - 将列名保存到MS Access的电子表格中
有9列被跳过的10列,我也将spreedsheet分开以允许第一行有标题,我将如何填充我的spreedsheet的第一行与我的数据库的列名称? 此外,如果直接通过代码分配名称,而不是从数据库传递列标题,那也没关系。
我的代码:
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中的字段出来,让所有的数据拟合在列?
感谢您的帮助,
安迪
是否有直接通过代码设置字段中数据的方法,即单元格A1 =“Rank”等? – Andy 2015-04-04 14:13:55
是...使用第1行的范围。 – Gustav 2015-04-04 15:21:38