Oracle to excel vba

 

mrzv

Пользователь

Сообщений: 44
Регистрация: 27.07.2015

#1

31.08.2018 12:11:55

Здравствуйте, раньше не имел дела с подключением к БД. Прошу помочь.
На просторах нашего форума нашел вот такую строку подключения

Код
Set cn = CreateObject("ADODB.Connection")
       cn.Open "Provider=MSDAORA.1;Data Source=***;Password=***;User ID=***"

но как настроить под свой лад не пойму. На счет Data Source=***;Password=***;User ID=*** все понятно
А вот Provider какой нужно использовать?
Я установил драйвер с сайта oracl «Oracle in instantclient_18_3» имя его «SQORA32.DLL».  

 

ivanok_v2

Пользователь

Сообщений: 712
Регистрация: 19.08.2018

Пример 1

ConnectionString для всех языков програмирования однаковая.
если вы подключаетсь через другое ПО,  значить нужные драйвера уже есть.

 

mrzv

Пользователь

Сообщений: 44
Регистрация: 27.07.2015

#3

31.08.2018 13:01:35

Цитата
ivanok_v2 написал:
если вы подключаетсь через другое ПО,  значить нужные драйвера уже есть.

Как тогда определить какой драйвер мне нужно использовать?

 

Nordheim

Пользователь

Сообщений: 3154
Регистрация: 18.04.2017

Я подключаюсь так «Provider=msdaora»

«Все гениальное просто, а все простое гениально!!!»

 

sokol92

Пользователь

Сообщений: 4445
Регистрация: 10.09.2017

#5

31.08.2018 13:14:12

Код
Provider=ORAOLEDB.ORACLE

Владимир

 

mrzv

Пользователь

Сообщений: 44
Регистрация: 27.07.2015

#6

31.08.2018 13:17:35

Вот такую ошибку мне выдает на строке подключения

Код
Set cn = CreateObject("ADODB.Connection")
       cn.Open "Provider=ORAOLEDB.ORACLE;Data Source=192.168.200.253:1521/xe;Password=org;User ID=pqw2"

Run-time error 3706
Не удается найти указанный поставщик.Вероятно, он установлен неправильно.

Изменено: mrzv31.08.2018 13:20:59

 

sokol92

Пользователь

Сообщений: 4445
Регистрация: 10.09.2017

Установите клиент Oracle в полном объеме. По умолчанию указанный выше драйвер может и не устанавливаться. Кроме того, учтите, что разрядности (32- или 64-) клиента Oracle и MS Office должны совпадать.

 

sokol92

Пользователь

Сообщений: 4445
Регистрация: 10.09.2017

Проверить доступность провайдера можно через Меню/Данные/Из других источников/Из мастера подключений/Дополнительно (путь дан для Excel 2016). Имя провайдера: Oracle Provider for OLE DB.Там же можно протестировать его работоспособность.

Изменено: sokol9231.08.2018 14:22:37

 

mrzv

Пользователь

Сообщений: 44
Регистрация: 27.07.2015

#9

31.08.2018 15:51:51

Спасибо за совет

Цитата
sokol92 написал:
через Меню/Данные/Из других источников/Из мастера подключений/Дополнительно (путь дан для Excel 2016)

Я создал подключение ODBC DNS посмотрел там строку подключения . Вставил её в свой код и все получилось. Только вот русские буквы вопросами…

Код
cn.Open "ODBC;DBQ=192.168.200.253:1521/XE;UID=orga;PWD=a546;DSN=ALGO"
 

mrzv

Пользователь

Сообщений: 44
Регистрация: 27.07.2015

#10

31.08.2018 16:21:48

Вот такой код, я получаю нужную мне информацию, но кириллица вопросами. Что я делаю не так?

Код
Sub ImpOracle()
Set cn = CreateObject("ADODB.Connection")
       cn.Open "ODBC;DBQ=192.168.200.253:1521/XE;UID=orga;PWD=a546;DSN=ALGO"
'========================================================================================
sSql = "select partner_short_name, trunc(OUTCOME_DATE_SALE) d, sum(roh.sum_w_nds) s,count(1) h from t_partner p, T_REMOTE_ROZNICA_OUTCOME_HEAD roh where ROH.REMOTE_PARTNER_ID = p.PARTNER_ID and trunc(OUTCOME_DATE_SALE) between sysdate - 3 and sysdate group by partner_short_name, trunc(OUTCOME_DATE_SALE)"

Set Rs = GetRs(sSql, cn)
Sheets("Лист1").[a1].CopyFromRecordset Rs
Rs.Close
Set Rs = Nothing
End Sub

Function GetRs(sstr, cn)
Set rstdata = CreateObject("ADODB.Recordset")
    rstdata.Open sstr, cn
    Set GetRs = rstdata
Set rstdata = Nothing
End Function

весь код взял из этой статьи https://www.planetaexcel.ru/forum/index.php?PAGE_NAME=message&FID=1&TID=60251

 

sokol92

Пользователь

Сообщений: 4445
Регистрация: 10.09.2017

Вы, похоже, подключили провайдер Microsoft, а не Oracle. Мы всегда работали с провайдером Oracle.

 

mrzv

Пользователь

Сообщений: 44
Регистрация: 27.07.2015

#12

03.09.2018 15:29:03

И так с проблемой провайдера я разобрался
Криво стояли драйвера oracle
Последний раз когда я их устанавливал я качал их вот отсюда

http://www.oracle.com/technetwork/database/windows/downloads/index-090165.html

скачивал вот этот файл:
64-bit ODAC 12.2c Release 1 (12.2.0.1.1) for Windows x64
[Released August 3, 2018]

ODAC122011_x64.zip — 406 MB (426,617,132 bytes)

В этом архиве есть нормальный setup

Правильная строка подключения выглядит вот так:

Код
Set cn = CreateObject("ADODB.Connection")
cn.Open "Provider=OraOLEDB.Oracle;Data Source=192.168.200.253:1521/XE;User ID=***;Password=***"

что касается кодировки при использовании DSN вместо Provider, то мне так и не удалось разобраться. Но на мой взгляд способ подключения через Provider более правильный.

Спасибо всем за помощь.

Изменено: mrzv03.09.2018 15:30:00

 

sokol92

Пользователь

Сообщений: 4445
Регистрация: 10.09.2017

 

bedvit

Пользователь

Сообщений: 2477
Регистрация: 02.04.2015

Виталий

#14

03.09.2018 23:46:15

Владимир, работаем тоже с родными драйверами Oracle. Microsoft не используем.

«Бритва Оккама» или «Принцип Калашникова»?

One rather old application I’ve supported for several years loads data from Excel spreadsheets into a reporting database. These Excel spreadsheets have always been manually updated by several users. However, because the data that the users are entering into these spreadsheets are first being entered into another separate application database, these users have been doing double-entry – a redundant process which can be easily remedied by various means.

Ideally, the solution for this problem would be to extract the data from the application database and load it into the reporting database using an SSIS package. Unfortunately, that would require some redevelopment of the application which loads data into the reporting database, and we (and the customers) have no bandwidth for that. So I came up with a quick workaround that made everyone happy – using a VBA macro to automatically populate the spreadsheets with data when the users open them.

The tricky part here was getting Excel to connect to Oracle with the least amount of work having to be done on the users’ PCs, which are remote from my location.

First of all, since these users don’t require SQL Plus or any development tools for Oracle, the full client software was unnecessary. Also, the Oracle Instant Client could be pushed to the users with Altiris Deployment Solution.

I had the Instant Client software installed on the PCs, then I added the requisite database connection information to the tnsnames.ora file.

Nota bene: In the Instant Client (or at least in our setup, using version 11.2.0.4) the tnsnames file is in
C:oracleinstantclient_11_2_0_4 rather than in C:oracleproduct11.2.0.4client_1NETWORKADMIN as it often would be in the full Oracle client.

The connection in VBA was simple enough, but not immediately obvious – notice that the connection string includes “Microsoft ODBC Driver for Oracle” rather than an Oracle driver; even though this is used, no ODBC connection needs to be set up in the ODBC Data Source Administrator. It is only imperative that the proper entries exist in the tnsnames.ora file, and that the Microsoft ActiveX Data Object Library is installed and referenced in Excel. (Add References by navigating to Tools –> References in the VBA editor in Excel.)

Excel References

In a subroutine, this code was used to connect to the database and pull data.

    Dim SQL_String As String
    Dim dbConnectStr As String
    Dim con As New ADODB.Connection
    Dim recset As New ADODB.Recordset
    Dim strUid As String
    Dim strPwd As String
    Dim strEnv As String
    Dim strDSN As String
    Dim iRow As Integer    

    strEnv = "prod"
    strUid = "username"
    strPwd = "password"

    If strEnv = "prod" Then
        strDSN = "(prod database net_service_name* from tnsnames)"
    Else
        strDSN = "(dev database net_service_name* from tnsnames)"
    End If

    dbConnectStr = "Driver={Microsoft ODBC for Oracle}; " & _
            "Server=" & strDSN & ";" & _
            "uid=" & strUid & ";pwd=" & strPwd & ";"

    con.ConnectionString = dbConnectStr
    con.Open   

    SQL_String = "(insert SQL query here)"

    recset.Open SQL_String, con

    iRow = 0
    Do While Not recset.EOF
         'Have a loop here to go through all the fields
        Sheet1.Range("A" & iRow).Value = recset.Fields("colname") ' colname = Column Name from SQL query

        ' &c. ...

        iRow = iRow + 1
        recset.MoveNext
    Loop

    recset.Close
    con.Close

* net_service_name

Dear Friends,

Using Excel Macros (VBA) you can connect to Databases like SQL, Oracle or Access DB. In this Article, I will teach you, how you can do a connection with a Oracle Server.
We can do connection with Oracle either by giving SID (Oracle System ID) or Service Name. Whichever is available for the connection, we can use them to connect to the Oracle Database.

Prerequisite

Before running the below code, you need to Add reference for ADODB Connection. If you do not know how to add references for ADODB connection in Excel workbook, follow below steps.

Step to Add ADODB Connection References in Excel

1. Go to VB Editor Screen (Alt+F11)
2. Tools –> References…
3. From the List of Available References Select “Microsoft ActiveX Data Objects 2.0 Library” You can select 2.0 Version or any other higher version of this reference.
4. Click OK

  Connection String with SID 
Connection String with Service(DB Name) 

Oracle Connection String with SID:

Use the below Code for connecting to the Oracle Database.


Sub Ora_Connection()
Dim con As ADODB.Connection
Dim rs As ADODB.Recordset
Dim query As String
Set con = New ADODB.Connection
Set rs = New ADODB.Recordset
'---- Replace below highlighted names with the corresponding values
strCon = "Driver={Microsoft ODBC for Oracle}; " & _
"CONNECTSTRING=(DESCRIPTION=" & _
"(ADDRESS=(PROTOCOL=TCP)" & _
"(HOST=Your Host Name)(PORT=Port Number))" & _
"(CONNECT_DATA=(SID=SID of your Database))); uid=User ID; pwd=Password;"
'---  Open   the above connection string.
con.Open (strCon)
'---  Now connection is open and you can use queries to execute them. 
'---  It will be open till you close the connection
End Sub

Oracle Connection String with Service:

Use the below Code for connecting to the Oracle Database.



Sub Ora_Connection()
Dim con As ADODB.Connection
Dim rs As ADODB.Recordset
Dim query As String
Set con = New ADODB.Connection
Set rs = New ADODB.Recordset
'---  Replace below highlighted names with the corresponding values
strCon = "Driver={Microsoft ODBC for Oracle}; " & _
"CONNECTSTRING=(DESCRIPTION=" & _
"(ADDRESS=(PROTOCOL=TCP)" & _
"(HOST=Your Host Name)(PORT=Enter Port Number))" & _
"(CONNECT_DATA=(SERVICE_NAME=database))); uid=Enter User ID; pwd=Enter Password;"
'---  Open the above connection string.
con.Open (strCon)
'---  Now connection is open and you can use queries to execute them.
'---  It will be open till you close the connection
End Sub

Read this Also:

  • How to Connect to SQL Database using Excel Macros
  • How to Connect to Oracle Database using Excel Macros
  • How to Connect to Access Database using Excel Macros
  • Remove From My Forums
  • Question

  • I want to import data into MS excel 2010 from SQL developer (Oracle) using VBA macro

    I am using below code but not able to connect to SQL devevloper.

    Kindly help.

    Sub ImportData() Sheets("sheet1").Select With ActiveSheet.ListObjects.Add(SourceType:=0, Source:= _ "OLEDB;Provider=MSDAORA.1;User ID=MY_USER;password= MY_PW;Data Source=sourceName", Destination _ :=Range("$A$1")).QueryTable .CommandType = xlCmdSql .CommandText = "Select Main.[ID],Main.[Count1] From Main Where Main.[Count1] > 25" .RowNumbers = False .FillAdjacentFormulas = False .PreserveFormatting = True .RefreshOnFileOpen = False .BackgroundQuery = True .RefreshStyle = xlInsertDeleteCells .SavePassword = False .SaveData = True .AdjustColumnWidth = True .RefreshPeriod = 0 .PreserveColumnInfo = True .Refresh BackgroundQuery:=False End With End Sub

Answers

    • Proposed as answer by

      Thursday, February 18, 2016 9:23 AM

    • Marked as answer by
      Edward8520Microsoft contingent staff
      Tuesday, February 23, 2016 7:10 AM

Понравилась статья? Поделить с друзьями:
  • Oracle to excel 2010
  • Oracle sql developer экспорт в excel
  • Oracle sql developer выгрузить результат запроса в excel
  • Oracle sql developer import from excel
  • Oracle sql and excel