Database Connection Manager

Connect to SQL databases and import/export data with error handling

631 views

Perfect For:

  • Database integration
  • SQL queries
  • Data synchronisation
VBA Code
Sub ConnectToDatabase()
    Dim conn As Object
    Dim rs As Object
    Dim ws As Worksheet
    Dim sql As String
    Dim connectionString As String
    Dim col As Long

    ' Database connection string (modify as needed)
    connectionString = InputBox("Enter connection string:" & vbCrLf & _
        "Example: Provider=SQLOLEDB;Data Source=server;Initial Catalog=database;Integrated Security=SSPI;")

    If connectionString = "" Then Exit Sub

    ' SQL query
    sql = InputBox("Enter SQL query:", "SQL Query", "SELECT * FROM TableName")
    If sql = "" Then Exit Sub

    ' Create connection
    Set conn = CreateObject("ADODB.Connection")
    Set rs = CreateObject("ADODB.Recordset")

    On Error GoTo ErrorHandler

    ' Open connection
    conn.Open connectionString

    ' Execute query
    rs.Open sql, conn

    ' Create new worksheet
    Set ws = Worksheets.Add
    ws.Name = "DBData_" & Format(Now, "mmdd_hhmm")

    ' Add column headers
    For col = 0 To rs.Fields.Count - 1
        ws.Cells(1, col + 1).Value = rs.Fields(col).Name
    Next col

    ' Copy data
    ws.Range("A2").CopyFromRecordset rs

    ' Format the data
    With ws.Range("A1").CurrentRegion
        .Font.Name = "Arial"
        .Font.Size = 10
        .Borders.LineStyle = xlContinuous
    End With

    ws.Rows(1).Font.Bold = True
    ws.Columns.AutoFit

    ' Clean up
    rs.Close
    conn.Close
    Set rs = Nothing
    Set conn = Nothing

    MsgBox "Database query executed successfully!"
    Exit Sub

ErrorHandler:
    MsgBox "Database error: " & Err.Description
    If Not rs Is Nothing Then rs.Close
    If Not conn Is Nothing Then conn.Close
End Sub

Related Topics

database sql connection import export

Need Custom VBA Solutions?

Our AI-powered VBA generator can create custom code tailored to your specific requirements in seconds.

Free AI generations every month — top up with credit packs anytime

Related Templates

More VBA templates in the same category

Beginner

Data Processing & Cleanup

Remove duplicates, clean data formats, and standardise entries

View Template
Intermediate

CSV Import with Data Types

Import CSV files with automatic data type detection and formatting

View Template
Intermediate

Timesheet & Attendance Tracker

Track employee working hours, overtime, absences, and holidays with automatic calculations, weekl...

View Template