gpt-3.5-turbo-0613· openai
Suzhen/CodeChat
帮我写一段vba代码 帮我从一个accdb数据库查询出数据 然后把数据写到excel表sheet1里面
- User
帮我写一段vba代码 帮我从一个accdb数据库查询出数据 然后把数据写到excel表sheet1里面
- Assistant
Sure, here's an example of VBA code that connects to an accdb database, executes a query, and writes the results to an Excel sheet named "Sheet1":
Sub GetDataFromAccess() ' Declare Variables Dim conn As Object Dim rs As Object Dim strDBPath As String Dim strSQL As String Dim i As Integer ' Set the path to the database strDBPath = "C:\your\database.accdb" ' Set the SQL query to retrieve data strSQL = "SELECT * FROM yourTable" ' Create a new Connection object Set conn = CreateObject("ADODB.Connection") ' Open the connection conn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" & strDBPath & "';" ' Create a new Recordset object Set rs = CreateObject("ADODB.Recordset") ' Open the recordset using the SQL query rs.Open strSQL, conn ' Clear existing data from Sheet1 Sheets("Sheet1").UsedRange.ClearContents ' Write the field names from the recordset to the first row of Sheet1 For i = 1 To rs.Fields.Count Sheets("Sheet1").Cells(1, i).Value = rs.Fields(i - 1).Name Next i ' Write the data from the recordset to Sheet1 starting from the second row Sheets("Sheet1").Range("A2").CopyFromRecordset rs ' Close the recordset rs.Close ' Close the connection conn.Close ' Cleanup Set rs = Nothing Set conn = Nothing MsgBox "Data imported successfully." End Sub