我在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