hiko-blog

VBA業務改善

MENU

Oracle ODBCドライバを使用する例

Sub GetDataFromAccess()

'Microsoft ActiveX Data Objects 2.8 Library」をチェック


    Dim conn As Object
    Dim rs As Object
    Dim strConnection As String
    Dim strSQL As String

    ' Create a new ADODB connection object
    Set conn = CreateObject("ADODB.Connection")
    
    ' Create a new ADODB recordset object
    Set rs = CreateObject("ADODB.Recordset")
    
    ' Connection string with all necessary information
    strConnection = "Driver={Oracle in OraClient11g_home1};" & _
                    "Dbq=YourDatabaseName;" & _
                    "Uid=YourUsername;" & _
                    "Pwd=YourPassword;"

    ' Open the connection
    conn.Open strConnection
    
    ' SQL query to retrieve data
    strSQL = "SELECT * FROM YourTableName"
    
    ' Open the recordset
    rs.Open strSQL, conn, 3, 1

    ' Loop through the recordset and print the data to the immediate window
    Do While Not rs.EOF
        Debug.Print rs.Fields(0).Value
        rs.MoveNext
    Loop
    
    ' Close the recordset and the connection
    rs.Close
    conn.Close

    ' Clean up
    Set rs = Nothing
    Set conn = Nothing
End Sub