3
我已經創建了一個模塊,使用存儲過程從SQL數據庫中讀取數據,並且獲取所有必需的數據,但是我的要求是我也需要所有列名稱/標題。而且我無法對名稱進行硬編碼,因爲我正在將數據行轉換爲存儲過程中的列。如何獲取VBA中的列名?
這是我寫的代碼:
ConnStr = "PROVIDER=SQLOLEDB.1;"
ConnStr = ConnStr & "DATA SOURCE=" & dataSrc & "; INITIAL CATALOG=" & iCatalog & "; "
ConnStr = ConnStr & "User ID = " & dbUserId & "; Password = " & dbPassword
On Error GoTo ErrHandler
DBConn.Open ConnStr
' Create a recordset object.
Dim rsCounter As ADODB.Recordset
Set rsCounter = New ADODB.Recordset
Dim startDate As String, endDate As String, query As String
query = "Exec ReadCntrs 0, '12/01/2011', '12/30/2011'"
With rsCounter
' Assign the Connection object.
.ActiveConnection = DBConn
.Open query
' Copy the records into cell A1 on Sheet1.
Sheet1.Range("A1").CopyFromRecordset rsCounter
' Tidy up
.Close
End With
DBConn.Close
Set rsCounter = Nothing
Set DBConn = Nothing
ExitHere:
On Error Resume Next
DBConn.Close: Set DBConn = Nothing
Err.Clear
Exit Sub
ErrHandler:
MsgBox Err.Number & Err.Description, vbExclamation
Resume ExitHere
End Sub