Excel vba odbc connection

RRS feed

  • Remove From My Forums
  • Question

  • Hi,

    I cannot figure out how to create connection with VBA and ODBC to SQL db. I need to retrieve data from the DB. I tried to find help but I failed.
    Thank you for your help

All replies

  • Thank you, however Im looking for DAO way of connection. I cannot find complete example of how to connect do database using DAO :(

    I have found this:

    Dim ws As Workspace
    Dim db As Database
    Dim strConn As String

    ‘ The «DSNName» is what ever the dsn appears as
    Set ws=DBEngine.Workspaces(0)
    strConn = «ODBC;DSN=» & DSNName & «;UID=» & _
    UserName & «;PWD=»
    Set db=ws.OpenDatabase(«», False, False, strConn

    But where should I add URL of DB? I dont understand :(

  • Hi

    The DSNName should hold the SQL Server’s IP/URL

    strConn = «ODBC;DSN=» & DSNName & «;UID=» & _
    UserName & «;PWD=»
    Set db=ws.OpenDatabase(«», False, False, strConn

    I am not sure if SQLServer Supports all feautres of DAO. If you getting the required output go ahead. Or else please move to ADO


    http://www.vbadud.blogspot.com

  •  Well, I would try ADO but thats the same, I cannot get it work :(

    I tried:

    Dim cnn1 As ADODB.Connection
    Dim cnn2 As ADODB.Connection
    ‘ Open a connection using the Microsoft ODBC provider.
    Set cnn1 = New ADODB.Connection
    cnn1.ConnectionString = «driver={SQL Server};» & _
    «server=localhost;uid=administrator;pwd=a»
    cnn1.Open

     //why there is no database specified?

    But it retrives error that server doesnt exist. I really dont understand what is the driver.

    Could please somebodz explain it to me: server= here should be URL. uid=username to SQL, pwd=password to SQL. But there is no DB selection..Im hopeless :(

    I would be extremely grateful to working example on connection to local SQL server. Thank you in advance

  • Plaase, anyone, help me with that:

    Sub test()

    Dim userID As String
    Dim pwd As String

            On Error GoTo errHandler
        Set conn = CreateObject(«ADODB.Connection»)
        connstr = «Driver={SQL Server};Server=localhost;Database=test;Uid=test;Pwd=test;»

            conn.Open connstr

                If Not rcset.EOF Then
            MsgBox rcset.Fields(0).Name & «-» & rcset.Fields(0).Value
        End If

        exitSub:
        rcset.Close: Set rcset = Nothing
        conn.Close: Set conn = Nothing
        MsgBox «Your data connection is working.», vbOKOnly + vbInformation, «Info»
    errHandler:
        MsgBox Err.Number & «-» & Err.Description, vbOKOnly + vbExclamation, «Error»
    End Sub

    Im still getting server doesnt exist or connection refused :(

Содержание

  1. What I need to know
  2. Monday, 28 November 2011
  3. Connecting to postgres from Excel (visual basic)
  4. 5 comments:
  5. How to execute PostgreSQL function from VBA code?
  6. 3 Answers 3
  7. Related
  8. Hot Network Questions
  9. Subscribe to RSS
  10. Pragmateek
  11. A geek on his way to IT pragmatism
  12. Using an Access, MySQL, PostgreSQL or SQLite database from VBA
  13. Introduction
  14. Data schema
  15. MySQL
  16. Installation
  17. Подключение Excel к PostgreSQL через VBA
  18. 3 ответы
  19. How to Connect Excel to PostgreSQL? Easy Ways to Load Data
  20. Table of Contents
  21. What is PostgreSQL?
  22. Key Features of PostgreSQL
  23. What is Microsoft Excel?
  24. Key Features of Microsoft Excel
  25. Methods to Connect Excel to PostgreSQL
  26. Method 1: Integrating Excel to PostgreSQL using ODBC Drivers
  27. Step 1: Install ODBC Drivers for PostgreSQL
  28. Step 2: Configure Postgres ODBC Driver in Excel
  29. Step 3: Authorise Connection with PostgreSQL
  30. Step 4: Load Data in Microsoft Excel
  31. Method 2: Integrating Excel to PostgreSQL via CSV Files
  32. Step 1: Excel File Conversion
  33. Step 2: CSV File Connection
  34. Step 3: Data Import
  35. Conclusion

What I need to know

Monday, 28 November 2011

Connecting to postgres from Excel (visual basic)

I am trying to insert & update records from Excel (visual basic) into a postgres table but am having problems connecting to postgres.
I am able to build querries in Excel no problem.

The postgres documentation give the following example to connect.

‘Open the connection
cn.Open «DSN= ;» & _
«UID= ;» & _
«PWD= ;» & _
«Database= «

I assume that the UID, PWD and Database are the same as the ones I would use in setting up the data source queries. the DSN is where I seem to fall down..

when I set up the datasource queries I specify «localhost» as the Server and 5432 as the Port
so I have tried using localhost:5432 as the DSN; so my code looks like:

Sub UpdateRecord()
Dim cnn As ADODB.Connection
Dim rst As ADODB.Recordset

‘Open the connection
cnn.Open «DSN=localhost:5432;» & _
«UID=postgres;» & _
«PWD=password;» & _
«Database=postgres»
End Sub

as the DSN but get
«Run Time Error 91»
«Object variable or With block variable not set

any ideas on what I am doing wrong??

Your DSN is wrong. But you knew that. You are using the ODBC driver and the DSN refers to the name you registered your PostgreSQL data source in ODBC manager (not the PostgreSQL server).

So if you registered it as MyLocalPgServer, then that would be what you use for DSN

Did you try connecting to the Postgres database via Excel’s get external data, data source GUI and/or, as Regina commented, creating a datasource that connects to the database? I haven’t used the VBA approach but I’ve used the former to get PostgreSQL query results into Excel for charting. I haven’t used VBA because there’s a lot more functionality available in PostgreSQL queries and procedures.

For whatever weird reason, your

line got turned into a hyperlink with the contents

Ah. the @ sign. Microsoft copy and paste? Or some other?

I have solved the Excel to Postgres using VB connection problem.
MS query is fine for doing reads from your database but it is sometimes usefull to write records from excel.

Here for others to use is the macro..
Sub UpdateRecord()
Dim cnn As New ADODB.connection
Dim rst As New ADODB.Recordset
‘dim cnn.ConnectionString string

cnn.Open «Driver=;DSN=postgres;Server=localhost;Port=5432;UID=postgres;PWD=password; Database=postgres;» & _
«READONLY=0;PROTOCOL=6.4;FAKEOIDINDEX=0;SHOWOIDCOLUMN=0;ROWVERSIONING=0;SHOWSYSTEMTABLES=1»

‘dropTable = «DROP TABLE IF EXISTS nyse.blobtable»
‘createTable = «CREATE TABLE nyse.blobtable (id INTEGER , myblob char(2), myBlobName VARCHAR(300))»
until
insertTable = «INSERT INTO nyse.customer» & _
» VALUES (customer.number,customer.name,customer.addr1,customer.addr2,customer.city,customer.postalcode,customer.country)»

‘ Execute queries and prepare blob writing

dropResult = cnn.Execute(dropTable)
createResult = cnn.Execute(createTable)
insertResult = cnn.Execute(insertTable)

I have used the add and drop table commands just to illustrate that you can do almost anything in the database from excel.

Источник

How to execute PostgreSQL function from VBA code?

How can I execute a function named Test1 that is stored in PostgreSQL from VBA code?

For example, we have a function definition as follows:

Now I’m trying to execute this function this way:

But I’m getting Syntax Error near FROM . I have no idea how to execute this, how can it be done?

3 Answers 3

You can use an Access «pass-through» query for your PostGreSQL function.

I created your function and table on my PostGreSQL server. Then created a new pass-through query in Access. I used a PostGreSQL statement for the query’s SQL property.

(I didn’t need a FROM clause.)

On the query property sheet, I assigned the ODBC connection string, and chose Yes for the «Returns Records» property. The query can then be run from the Access user interface, or used from VBA code to open a DAO recordset based on that query.

It is failing because you have set dbs to the current database. When you execute this statement access will look for the table “Test1()” and throw a hissy fit when it cant find it.

I am unsure as to how to do this with postgre but this is how I have gone about doing a similar thing with SQL server so I assume it will be the same but with a different connection string

Way old post nonwithstanding, I came here via Google and finally managed to put together a function that works for me, it may help someone else with the same problem: In a public Module in MS Access, save the following

Hot Network Questions

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.3.20.43331

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Pragmateek

A geek on his way to IT pragmatism

Using an Access, MySQL, PostgreSQL or SQLite database from VBA

Introduction

Note to pedantic guys: yes Access is not a database engine, only the graphical front-end to Jet/ACE, but we’ll stand with this simplification. 🙂

The sample application (Excel + VBA) and the SQL source code are available in this ZIP archive: VBA_Databases_Source.zip.

If you are an advanced VBA developer who builds applications that manage a non trivial amount of data odds are good you are using an Access database to store them.
If this setup perfectly fits your current needs, you completely master it, you’re not experiencing any issue and your needs won’t evolve in the near future you can skip this article and continue enjoying your system. 😉

Indeed, do you really need a new database management system (DBMS)?
Often the only argument in favor of migrating to other DBMS is they are “better”; while it’s true for some technical capabilities, it may not be regarding other “metrics” like simplicity: Access is easy to understand and manage for non IT staff and is often installed with default business workstation setup along with the rest of the Office suite.

So let’s say you have strong reasons to migrate to a new DBMS because you’ve come to the point where you feel you need support for at least one of the following features: interoperability, big storage, high concurrency (hundreds of users) and/or high performance, and Access starts to become a part of the problem.
So what can you do if you want to enhance the quality of your database without making your total cost of ownership (TCO) explode?

Your TCO is essentially made of:

  • licensing costs: limiting them is quite simple: using a free, usually open-source, database and paying only for support
  • management costs: they are by far bigger than the licensing costs and are directly impacted by the complexity of the DBMS; so you need a simple DBMS that you’ll be able to setup and manage yourself as you used to do with Access without the help of system or database administrators
  • development costs: every additional change to your current schema or VBA implementation to fit the new DBMS will have a cost; so we want things to be transparent with zero additional development, which in particular means a standard SQL-based DBMS.

While the equation may seem a little complex it has at least three solutions:

  • SQLite is the ideal candidate if you’re happy with the “single-file” model, you don’t have high concurrency constraints, and your only needs are interoperability (with Mac OS, Linux, Unix…), bigger storage and/or costs savings,
  • MySQL and PostgreSQL: if you need support for high-concurrency, really big storage (e.g. tens of GBs), advanced user-management, performance fine tuning and other advanced features you’ll have to jump out of the single-file world.
    If you don’t have specific requirements then MySQL and PostgreSQL will appear similar to you and equally do the job. However, in this kind of situation, I have a preference for MySQL, not because its inherent capabilities would be superior (as I’ve said MySQL and PostgreSQL are roughly equivalent for simple setups), but because, as the reference open-source DBMS for years, MySQL benefits from a huge community and toolbox. Moreover, while you’ll sure find the tools to work in good conditions with PostgreSQL, if you ever need to justify your choice to your hierarchy you’ll be in a better position if you choose the standard solution instead of the challenger.
    But as I’m not sectarian, and for completeness, I’ll cover both.

In this article I’ll quickly cover the setup of these three DBMS (with links to other resources for more extensive instructions) and illustrate their usage with a small VBA application, a revolutionary todo-list manager, that uses Access too.

Data schema

The data schema used by our application is really basic: one table with 3 columns:

  • Description : a textual description of the task,
  • Category : a tag that will help further categorization of the bunch of tasks you’ve created,
  • Due date : the limit date for accomplishing the task, after you could be in trouble with your boss!

Here is how it looks like in Access:

Access Tasks Table

The equivalent in Access SQL dialect is:

MySQL

Installation

You can download the MSI installer from here: MySQL.
Once downloaded start it and accept any Windows security popup that could appear.
Then you can follow this slide-show for further instructions:

Источник

Подключение Excel к PostgreSQL через VBA

Можно ли сделать запрос типа SELECT из VBA в Excel, чтобы я мог запросить базу данных PostgreSQL из Excel?

Если возможно, объясните мне, как подключиться к базе данных. Я искал в Google, но не нашел результатов.

3 ответы

Создайте таблицу или представление в PostgreSQL, описывающее нужные вам данные.

Используйте соединение ODBC или ADO из VBA для подключения к PostgreSQL. Если вы используете ODBC, вам нужно создать DSN через odbcad32.exe затем используйте DSN в VB, просто подключиться напрямую непросто.

ответ дан 23 мая ’17, 12:05

Вот некоторый код, который можно использовать в качестве справки. Надеюсь, поможет.

Даже для 64-битной Windows Excel VBA требует 32-разрядный драйвер ODBC.

Создайте DSN через %windir%SysWOW64odbcad32.exe . Действительно, набрав odbcad32.exe указывает на 64-битную версию, где вы не можете найти подходящие 32-битные драйверы по умолчанию.

Ответ @Craig (хороший и более подробный, чем ваш) уже указывает на 32-битную проблему. Вы действительно добавляете этому ответу какую-либо ценность? — Alexander

На самом деле я не мог подключить Excel к PostgreSQL через VBA с ответом Крейга, а также со всеми другими ответами на StackOverflow. Никто не упомянул потенциальную проблему с odbcad32.exe . Для кого-то это может быть очевидно, но не для меня, и, судя по количеству неотвеченных тем в Интернете, я думаю, что я не одинок. Надстройка Excel на Github не работает из-за проблемы с форматом, но формулировка отлично объясняет процедуру, которой нужно следовать. Если вы не хотите публиковать мой ответ, я не рассержусь, но несколько человек столкнутся с той же проблемой, что и я, в будущем. — Кандид

Не тот ответ, который вы ищете? Просмотрите другие вопросы с метками excel postgresql vba odbc ado or задайте свой вопрос.

Источник

How to Connect Excel to PostgreSQL? Easy Ways to Load Data

Related Articles

Table of Contents

Microsoft Excel is a spreadsheet program included in the Microsoft Office Suite. It’s compatible with Windows, Mac OS X, Android, and iOS. It simplifies the creation of text and numeric grids, formulas calculations, graphing tools, pivot tables, and the VBA Macro programming language (Visual Basic for Applications). Simple and advanced arithmetic operations and functions can be used to numerically manipulate grids of numbers organized in rows and columns.

Table of Contents

PostgreSQL, sometimes known as Postgres, is a free and open-source Relational Database Management System (RDBMS) that emphasizes extensibility and SQL conformance. Structured objects are used instead of documents to store data in PostgreSQL. It employs conventional SQL syntax and formatting.

There are a variety of methods for importing Excel data into a PostgreSQL database; some are simple, while others are more complicated, depending on the sort of data you receive and the format it is in. In this article, you will learn everything about Excel to PostgreSQL along with the process which you might want to carry out while using it to make the process run smoothly.

What is PostgreSQL?

PostgreSQL, or Postgres, is a free, open-source Relational Database Management System (RDBMS) that focuses on extensibility and SQL compliance. It was first released on July 8, 1996, and was developed at the University of California, Berkeley. It was the Ignes database’s successor. Instead of storing data in the form of documents, PostgreSQL uses Structured objects. It uses the standard SQL syntax and style.

It’s written in C and has a monolithic architecture, which means all of the parts are connected and work in a logical order. It provides community assistance and further assistance to some of its paid customers. Because of its novel backup systems, it is frequently employed in the Healthcare, Finance, and Industrial industries.

Key Features of PostgreSQL

PostgreSQL has some distinguishing characteristics that make it a viable alternative to other standard RDBMSs. The following are some of these characteristics:

  • PostgreSQL can handle a wide range of data, documents, and customization kinds.
  • It features a Monolithic Architecture, which means that all of the components function together automatically.
  • It’s perfect for transactional workflows like those found in bank systems, risk assessments, BI (Business Intelligence), and powering a variety of business applications.
  • Storage is reliable because of various fail-safes and redundancy.
  • Since it is open-source, anyone can utilize all of its features for free.
  • Since its processing capacity depends on the system it runs on, it has limited scalability.
  • It has a strong Access Control System with features such as row and column level security and multi-factor authentication with certificates.
  • It is ACID (Atomicity, Consistency, Isolation, and Durability) compliant and runs on major operating systems.

To learn more about PostgreSQL, you can check the official website here.

What is Microsoft Excel?

Microsoft Excel is a Spreadsheet Application that is part of the Microsoft Office Suite. It runs on Windows, Mac OS X, Android, and iOS devices. It makes text and numeric grids, calculation of formulas, graphing tools, pivot tables, and the VBA Macro programming language easier to create (Visual Basic for Applications). To numerically manipulate grids of numbers organized in rows and columns, simple and sophisticated arithmetic operations and functions can be utilized.

Microsoft Excel is a spreadsheet program that may be used to create tables and record data. The information can range from a daily planner to financial information about a company. It also facilitates data analysis and the production of visualizations based on spreadsheet data.

Key Features of Microsoft Excel

  • Paste Special: When copying data from one cell to another, the user can also copy formatting, value, formula, comments, and other items, as well as their combinations, depending on the user’s needs.
  • Conditional Formatting: This feature draws attention to trends in your data as they appear in your spreadsheet.
  • Excel Pivot Tables: These can be used to sort, count, total, or average data from a single large spreadsheet and display it in whatever way the user chooses in a new table.
  • Add Multiple Rows: Users can add multiple rows and columns to their spreadsheets at any moment in Microsoft Excel.
  • Print Optimisation: Print Preview, Fit to One Page, Altering Margins, Print Selection, Printing Headers, Portrait vs. Landscape, and Spreadsheet Design are all options for printing Excel sheets to your satisfaction.
  • Vertical/Horizontal Formula Extention: Excel’s biggest feature is its ability to scale vertically and horizontally. Excel will conduct the necessary calculations any number of times once the formula is correct.
  • Index-Match: One of the most powerful Excel function combinations is Index-Match. It can be used to look up a value in a large Data Table and return its equivalent in the table.
  • Filters: Microsoft Excel provides capabilities that let you analyze data based on your own requirements. Filters are the terms for these functionalities.
  • Flash Fill: While copying data, Excel offers suggestions for making specific changes. Consider the following scenario: you have two columns of names and you need to produce email addresses for each of them. While you’re selecting an email address for one row, Excel will propose email addresses for all of the other rows based on their names.

For further information on Microsoft Excel, check the official website here.

Hevo Data, a No-code Data Pipeline helps to load data from any data source such as Google Sheets, FTP, Google Search Console, SaaS applications, Cloud Storage, SDKs, and Streaming Services to a destination of your choice like PostgreSQL and simplifies the ETL process like Excel to PostgreSQL. It supports 100+ data sources (including 40+ free data sources) and is a 3-step process by just selecting the data source, providing valid credentials, and choosing the destination. Hevo not only loads the data onto the desired Data Warehouse/destination but also enriches the data and transforms it into an analysis-ready form without having to write a single line of code.

Its completely automated pipeline offers data to be delivered in real-time without any loss from source to destination. Its fault-tolerant and scalable architecture ensure that the data is handled in a secure, consistent manner with zero data loss and supports different forms of data. The solutions provided are consistent and work with different BI tools as well.

Check out why Hevo is the Best:

  • Secure: Hevo has a fault-tolerant architecture that ensures that the data is handled in a secure, consistent manner with zero data loss.
  • Schema Management: Hevo takes away the tedious task of schema management & automatically detects the schema of incoming data and maps it to the destination schema.
  • Minimal Learning: Hevo, with its simple and interactive UI, is extremely simple for new customers to work on and perform operations.
  • Hevo Is Built To Scale: As the number of sources and the volume of your data grows, Hevo scales horizontally, handling millions of records per minute with very little latency.
  • Incremental Data Load: Hevo allows the transfer of data that has been modified in real-time. This ensures efficient utilization of bandwidth on both ends.
  • Live Support: The Hevo team is available round the clock to extend exceptional support to its customers through chat, email, and support calls.
  • Live Monitoring: Hevo allows you to monitor the data flow and check where your data is at a particular point in time.

Sign up here for a 14-day free trial!

Methods to Connect Excel to PostgreSQL

There are many methods to transfer data from Excel to PostgreSQL. You will gain an understanding of two of them.

Method 1: Integrating Excel to PostgreSQL using ODBC Drivers

Get & Transform (Power Query) can be used to connect to PostgreSQL from Excel using ODBC. This approach presupposes you’ve installed a PostgreSQL ODBC Driver.

Step 1: Install ODBC Drivers for PostgreSQL

The first step in Excel to PostgreSQL data transfer is to install ODBC Driver. The PostgreSQL ODBC 64-bit driver is available for download. On the machine where the Secure Agent is installed, install the PostgreSQL ODBC driver.

Step 2: Configure Postgres ODBC Driver in Excel

Expand the Get Data drop-down box after clicking Data in Excel. Select From Other Sources > From ODBC from the drop-down menu.

Choose your data source name in the From ODBC dialogue (DSN). You can expand the Advanced Options dialogue box and input the connection string for your Data Source if you haven’t yet established your ODBC Driver (without credentials, which are defined in the credentials dialogue box in the next step). You can also enter a SQL query that will be performed immediately after connecting to the data source. Click the OK button.

Select Database and input your credentials in the dialog box, then click Connect if you’re using a database Username or Password. Select Default or Custom and press Connect if your database is not password-protected or if you’ve previously entered your credentials in the ODBC Data Source settings.

Step 4: Load Data in Microsoft Excel

Select the table from which you wish to retrieve data in the pop-up box and click on Load.

The table’s data will be displayed in an Excel spreadsheet, where you can interact with it further.

You have successfully completed Excel to PostgreSQL data transfer via ODBC Driver.

Method 2: Integrating Excel to PostgreSQL via CSV Files

Step 1: Excel File Conversion

The first step in the CSV method in Excel to PostgreSQL data transfer is to Excel FIle Conversion. Open your file in Microsoft Excel if the file extension is xls or xlsx. This will need to be converted to a CSV file, which is a simple process. Simply Save As and modify the “Save as type:” to “CSV (*.csv)” before clicking Save. There is no need to change the file name to .csv because it will change automatically.

Step 2: CSV File Connection

Click Create and then Connection after right-clicking your Database Connection (or anyplace if your connections are empty). On the left, make sure the All tab is chosen, then scroll down to CSV. Now click Next.

Select the folder where you saved your CSV file from Microsoft Excel by clicking Browse. You’re choosing a folder rather than a file. All CSV files in that folder will be loaded by the connection. Finish by clicking the Finish button.

You should now notice a new connection, which is configured similarly to a standard connection. Each of the CSV files in your folder will be organized into a table with columns.

Step 3: Data Import

Data Import is the last step in the process of Excel to PostgreSQL data transfer. After you’ve established the connection, you may query the data using SQL syntax, just like any other table. This data can now be imported into your PostgreSQL Table. Select Export Data from the context menu of the table you want to import into PostgreSQL.

Click Next after selecting Database. Change the target container to the schema in PostgreSQL where your table resides. Click on the OK button.

Choose the target (table) for the data to be imported. Set the target column for each data column by clicking Columns. This will map automatically if you have headers in your data that match the table columns. Click the OK button. Now, Next should be selected.

Set the connection and Data Load options. Remove the option for truncating the target table if you only want to add data to the table rather than rewriting it. Now, Next should be selected.

After you’ve double-checked that the source and target are correct, click Start to begin the import.

The data from your PostgreSQL table is now available for selection.

You have successfully completed Excel to PostgreSQL data transfer via CSV files.

Conclusion

This article teaches you about Excel to PostgreSQL. It provides in-depth knowledge about the concepts behind every step to help you understand and implement them efficiently. If you want to transfer data into your desired Database/destination, then Hevo Data is the right choice!

Hevo Data provides users with a simpler platform for integrating data from 150+ sources such as Google Sheets, FTP, etc. for Analysis. It is a No-code Data Pipeline that can help you combine data from multiple sources. You can use it to transfer data from multiple data sources into your Data Warehouses, Databases such as PostgreSQL, or a destination of your choice. It helps you carry out ETL processes like Excel to PostgreSQL. It provides you with a consistent and reliable solution to managing data in real-time, ensuring that you always have Analysis-ready data in your desired destination.

Want to take Hevo for a spin? Sign Up for a 14-day free trial and experience the feature-rich Hevo suite firsthand. You can also have a look at our unbeatable pricing that will help you choose the right plan for your business needs!

Share your experience of learning about Excel to PostgreSQL! Let us know in the comments section below!

Источник

 

kkrasilov

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

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

#1

28.05.2018 10:14:56

Добрый день!
Хочу через vba работать с базами MySql.
Вроде все делал правильно, но никак не подключает.
В References добавил Microsoft ActiveX Data Odjects 6.0 Library
Установил MySql ODBC 8.0 Unicod Driver
И собственно сам код:

Код
Dim conn As Object
Set conn = New ADODB.Connection
conn.ConnectionString = "DRIVER={MySQL ODBC 8.0 Unicode Driver};SERVER=localhost;DATABASE=*;UID=root;PWD=*;"
conn.Open

*текущие база данных и пароль
Выдает ошибку Run-time error ‘-2147467259 Automation error
Буду благодарен за любой совет!

Изменено: kkrasilov28.05.2018 10:21:10

 

DenSyo

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

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

#2

28.05.2018 11:30:28

Код
DRIVER={MySQL ODBC 5.3 ANSI Driver};SERVER=SQLSRV;DATABASE=*;UID=root;PASSWORD=*;PORT:3306;charset=cp1251;Option=3;

так у меня подключается, попробуйте доп.параметры

 

БМВ

Модератор

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

Excel 2013, 2016

По вопросам из тем форума, личку не читаю.

 

kkrasilov

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

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

DenSyo, а библиотека Microsoft ActiveX Data Odjects 6.0 стоит?  

 

Doober

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

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

Разрядность драйвера и разрядность офиса совпадают?

 

kkrasilov

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

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

Doober, действительно, система стояла x64, драйвер скачивал так же x64, а офис по умолчанию стоял x32.
Переустановил офис с новой разрядностью, все работает!
Doober, спасибо!
Тему можно закрывать!
Нашел ещё хорошую статью по этой теме, мало ли кому понадобится —

http://bienabee.freshdesk.com/support/solutions/articles/1000017835-connecting-to-mysql-in-excel-doe…

 

Ametist69

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

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

#7

28.06.2019 11:15:13

Добрый день!

Столкнулся с той же проблемой, только ошибка другая:

Код выглядит вот таким образом

Код
Dim conn As Object
Set conn = New ADODB.Connection
conn.ConnectionString = "DRIVER={MySQL ODBC 8.0 ANSI Driver};SERVER=localhost;PORT:3307;DATABASE=my_db;UID=user_test;Pwd=12345;Option=3;"
conn.Open

Пишет что доступ пользователю запрещён, хотя в настройках самой БД пользователю user_test доступ предоставлен.
Разрядность системы, офиса и драйвера совпадает. Необходимая библиотека подключена.

Помогите пожалуйста разобраться.

Прикрепленные файлы

  • Снимок.JPG (19.4 КБ)

Изменено: Ametist6928.06.2019 11:26:53

 

doober

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

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

#8

28.06.2019 23:38:36

Цитата
Ametist69 написал:
user_test доступ предоставлен.

Сомневаюсь я однако если пароль верный.
С какого носта доступ разрешен?
localhost , %

<#0>

 

Ametist69

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

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

#9

09.07.2019 16:07:10

Проблема решилась, большое спасибо!
Если кому пригодится, вот рабочий код:

Код
Sub Подключение()

Dim cnnConnect As ADODB.Connection
Dim rstRecordset As ADODB.Recordset

Application.ScreenUpdating = False
Application.EnableEvents = False
Set cnnConnect = New ADODB.Connection
Set rstRecordset = New ADODB.Recordset
cnnConnect.Open "DRIVER={MySQL ODBC 8.0 Unicode Driver};SERVER=localhost;DATABASE=my_db;UID=user_test;PASSWORD=123456;PORT:3306;"
rstRecordset.Open Source:="SELECT * FROM my_table", ActiveConnection:=cnnConnect, CursorType:=adOpenDynamic, LockType:=adLockReadOnly, Options:=adCmdText
With Sheets(1).QueryTables.Add( _
        Connection:=rstRecordset, _
        Destination:=Sheets(1).Range("A1"))
        .Name = "Test_request"
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = True
        .BackgroundQuery = True
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .PreserveColumnInfo = True
        .Refresh BackgroundQuery:=False
End With
rstRecordset.Close
cnnConnect.Close
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
 

Александр Шульпинов

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

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

#10

28.01.2022 14:01:35

Добрый день. Подскажите пожалуста. При использовании Вашего кода выжает ошибку что на найдём источник и драйвер. Что делать?  

Do you dig what I am talking about?

In case you miss the outstanding promise of that title up here, you are about to discover a new world of capabilities and opportunities you have never imagined with Excel.

Most of the business application running our world’s economy (all organizations out there) – rely on a strong relational Database as the backbone of its information systems.

These Databases handle trillions of records, serving operational and analytical transactions and queries in a high speed, reliability, and flexibility.

It is only in the past 15 years or so that a new Database paradigm was introduced to handle today’s unique scale and social uses of applications of our time: Graph Database (I may write a Blog post about these new players one day).

Once you can program with VBA and work with an external Relational Database Management System (RDBMS) for your persistent data requirements – you can develop almost any business application you want.

Business applications with Excel?! Say WHAT?

I know some consultants do not approve Excel to be chosen as a business application platform to begin with, but I disagree with the belief that no business application can or should be developed with Excel and an external RDBMS.

In fact, I have been developing and delivering mission-critical business application for many years to customers around the world, mostly with Excel and MySQL RDBMS.

I am talking about systems to manage production planning and execution, human resources and training, banking (mortgage and investments products), sales management, Reinsurance brokerage and many others. These are highly cost-effective and reliable. Once I finish installation and initial guidance – the only reason for the customer to call back is for more solutions – not complaints.

So, the proof is in the pudding, or in other words, in solid and exceptionally reliable applications that run for years, in which the customer invested $20,000 instead of $40,000 had he approached a traditional software house for that application.

And yes, I develop using other technologies too, not only Excel VBA.

Let’s get you up to speed

Back in June of last year I published a Blog post about writing SQL queries over Excel tables. You should be familiar with that Blog post before reading on.

But even before that, if you feel you need to better understand what a relational Database is – go ahead and read my Blog post titled Understanding Relational Databases – The Basics.

Preparing the MySQL Database

If we want to work with an RDBMS, we need to have access to one.

I like MySQL and use it a lot but note that any standard RDBMS product out there will work just as well.

MySQL Community Edition is a free edition of the complete Database server and additional helpful tools that you can install on any laptop. It doesn’t have to be the same machine you are running Excel on, as long as you have access over a network from your Excel machine to the DB server machine.

Follow the MySQL instructions here to complete this step. I advise to install the complete package, at least install the MySQL Workbench and the MySQL Command Line Client in addition to the MySQL Server component.

Once you have MySQL Server installed and accessible, go ahead and define a user (in addition to the “root” user that is like the “admin” user in other products). Grant enough administrative roles (permissions) to CREATE and SELECT. Selecting the DBManager administrative role will serve you perfectly.

The MySQL Workbench is a Windows graphic user interface to work against the DB Server – use it for easy and intuitive experience.

As you can imagine, MySQL Server and MySQL Workbench are huge sophisticated and capable software products. While this post does not intend to cover MySQL usage, you will find plenty of tutorials for any popular task out there.

Setting up the Connection between MySQL Server and Excel

A server, unsurprisingly, is designed to serve many clients.

The concept is that clients submit requests to the server. The server caters for the requests and sends a response to the clients. This is known as a client-server architecture.

The MySQL Workbench you installed (and possibly used) is a client communicating with the MySQL Server. Same goes to the MySQL Command Line Client.

We want Excel to act as yet another client.

Clients communicate with servers over an agreed upon protocol. The protocol is the “language” they both understand and facilitates the effective communications between them.

Since Excel does not know the MySQL protocol, we need a middle-man translator to facilitate the communications between them.

The MySQL ODBC Connector is what we’re after and if you hadn’t installed it with the complete package earlier, go ahead and install it from here. Select the 32-bit Windows version even if your Windows is 64-bit. The ODBC Connector is to be installed on the client machine, that is, the machine you run your Excel on (regardless of where the MySQL Server is installed).

ODBC (Open Database Connectivity) is a standard application programming interface for accessing database management systems.

The MySQL ODBC Connector you installed “speaks” with the MySQL server in its proprietary protocol on one end, and “speaks” the standard ODBC protocol on the other end, in effect serving as our translator middle-man.

Referencing the ODBC Connector in your Excel VBA program

The last link in the chain we need to do is to bind an ODBC service to our VBA application, so that we can start creating objects and calling their methods to submit requests to the MySQL Server through the ODBC Connector in our VBA program.

This service is provided to us by Microsoft and it is called ADODB.

Let’s do an early binding to the ADODB service by referencing it in our VBA program. While in the VBA editor, select Tools -> reference in the upper menu and tick the Microsoft ActiveX Data Objects 6.1 Library (take the highest version you find if 6.1 isn’t listed).

Connecting Excel VBA to MySQL Database

If you want to better understand early binding vs. late binding – I have just the Blog post for you here!

That’s it! You now have a great setting for Excel to MySQL Server connectivity and you are now ready to start coding your first business application with MySQL. and this is demonstrated in part 2 of this Blog series here – click to continue.

Be sure to share this post with your friends and colleagues far and wide.



Run A Query On External Data(odbc) Criteria Based On Input Of A Ce — Excel

I have an access database that I would like to put a DATE into a cell and
have it auto run a query with that date criteria. I have done this with the
query wizard and manualy but would like to automate the process by just
typing the date and pressing the enter any one who could lead me in the
right direction or who has done this before I would appreciate the help

thank you TR

View Answers


Sql Server Odbc Error — Excel

I have an Excel 2000 sheet based on a MS Query to a SQL Server 2000 database.
When I refresh the query, the ODBC connection fails with this error:

SQLState: ‘01000’
SQL Server Error: 11001
[Microsoft][ODBC SQL Server Driver][TCP/IP Sockets][ConnectionOpen
(Connect()).
Connection failed:
SQLState: ‘08001’
SQL Server Error: 6
[Microsoft][ODBC SQL Server Driver][TCP/IP Sockets]Specified SQL Server not
found.

An Access database with links to this SQL Server data source works just
fine. I tested the ODBC connection and it works fine.

The problem cropped up after the database and Excel sheets were moved to a
new physical server.

I tried to edit the Query in hopes of recreating it from scratch but I can’t
see the Query because the ODBC error appears and won’t open the query editor.
How can I fix the error or open the query so I can manually recreate it?

Thanks!

—Art

View Answers


Ms Query Odbc Connection — Excel

I have an excel sheet that I have MS Query attatched to. Recently, our servers were renamed to something different. I have changed my ODBC connections on my computer and updated my other excel sheets to point to the correct server via Script Editor, however, on one particular spreadsheet, the script editor is disabled and I can’t update the path.\trap-true, etc.

How can I tell this worksheet to point to the new server? There has to be something in the background where I can tell it to go.

BTW…..I’ve tried opening the Query and because the new server is down, it will not connect to allow me to cut and paste the SQL code to another worksheet.

Please help

View Answers


Fetch Data From Oracle To Excel With Oracle Odbc Driver Using Vba — Excel

Is there anybody know how to extract data from Oracle RDBMS to a Excel worksheet using VBA. Is it possible to create a db connection & a query in VBA code? Please advise. Thanks in advance.

clam

View Answers


Filtering Odbc Data — Excel

I have created an ODBC link into an SQL server using the Import External Data
function in Excel 2003. The data is coming through without any problems
except that there is too much of it. Excel has a limit of 65,000 lines and
there is around 300,000 lines of data trying to get through, and the data I
want is at the bottom.

I want to put a filter on one of the columns in the table but don’t know
how. I can see the Edit Query box but i’ve never really used SQL before.

Can anybody help?

View Answers


Odbc Imports Numbers As Text — Excel

When I use ODBC to import data into Excel, all numbers come through with a
leading apostrophe so that Excel sees them as text.
e..g INSERT INTO [Sheet1$] VALUES (10) will come into Excel as ’10

View Answers


How Do I Export Data From Excel Into An Odbc Client / Or Plain Tex — Excel

I have an excel workbook containing many sheets, of which I wish to export
the data residing on one worksheet only. I would like to know how to do 2
things.
1) export the data into an email so that it appears as flat text, not an
embedded picture, so that I am able to have a robot scrape the data to go
into an HTML ODBC. There will be approx 6 columns by 60 lines and the
workbook has many macros embedded in it.
2) export the data directly into an HTML ODBC
I am not a developer, but asking the questions for one, so appreciate layman
terms if possible, but happy to accept any and all help.
Thanks

View Answers


Ora-12154 Tns Error For Odbc Connection Via Excel — Excel

I have set up an ODBC connection via the Admin tools under control panel and it connects fine.

However, when I try to use the same connection to update from Excel, I receive the error ORA-12154: TNS: could not resolve the connect identifier specified.

I have validated that the tnsnames.ora file is in my current path.

I’m using the Oracle in instantclient10_2 driver to create the ODBC Data Source.

Any help would be SOOOO appreciated!

Thanks!!
Andrea

View Answers


Embed Password In Vba For Odbc Connection — Excel

My code executes a query from an oracle db. Everytime I try to run it, it asks for the ODBC password. I was wondering if it’s possible to embed the password in the code so it doesn’t ask for it. Below is my attempt from piecing together what I found through googling, but does not seem to work. any help would be appreciated, thanks.

Code:

   Dim SQLStr As String
   Dim connection As ADODB.connection
   Dim rst As ADODB.Recordset
   Dim intRow As Integer

   SQLStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Range("DBPath") & ";Persist Security Info=False;" & _
                "Jet OLEDB:Database Password='kchu_6789';"
   Set connection = New ADODB.connection
   connection.Open SQLStr
   Set rst = New ADODB.Recordset

View Answers


Odbc Excel Driver Login Failed — Excel

Hello guys,

I have a problem for which I can not find a solution within the net.

I have an excel file that uses MSQuery to extract data from other excel files and a VBA that updates all the queries automatically when the file is opened. It works just perfect but the problem is that if I try to open the file from different computers I get the «ODBC Excel Driver login failed»

I have installed all add-ins on each computer and they all have one and the same version of excel.

Could anybody advise what the problem could be?

Thanks a lot!

View Answers


Updating Mysql Database With Excel Using Odbc? — Excel

Hi,

I have managed to export my SQL db to excel using the mysql ODBC driver but is there any way for me to update mySQL database using the ODBC driver?

View Answers


Refresh Pivot Same Time As Odbc Refresh — Excel

Hi

I have a spreadsheet connected to our in house system via ODBC. When I refresh sheet2(data) I need sheet1(summary) — which is a pivot table using the data from sheet2(data) to update as well.

Any help on how I could achieve would be great.

Many thanks

Jon D

View Answers


Preserving Data On Odbc Refresh — Excel

Hi,
I download a table from SAGE accounts package using an ODBC link and MSQuery.
I have a series of additional columns in which I manipulate the linked data in various ways.
At some later time I need to refresh the link. Typicaly this will add some new data, relink some existing data and some of the existing data will no longer meet the criteria of the Query and will «drop off». I need to preserve the manipulation of the retained «old» data and have some flag to tell the program that the «new» data needs to be manipulated.

An initial download brings about 300 records. Each refresh adds about 30 and drops off about 30 records.
I thought that this would be easy, but the refresh seems to destroy the row and column relationships so I get spurious results.
can anyone help me with this please?
John Southern

View Answers


Loop Thru And Delete All Odbc Connections — Excel

Hello,

I have a workbook that I created to import any table on our SQL server via ODBC and once I am done with table I completely clear the worksheet to it’s original state (as if I just inserted a brand new sheet) and before I import another table, I would like to be able to loop through all the existing connections and delete them. I attempted this with the code below, however I don’t really know how to work with the ODBC object model.

Code:

Sub DeleteConnections()
Dim Conn As ODBCConnection
For Each Conn In ThisWorkbook.Connections
      'Not sure what to put here. 
Next Conn
End Sub

Please HELP!!!

View Answers


Check Odbc Connection Before Refresh — Excel

Hi

I have an Excel spreadsheet linked through to a sql table via and ODBC connection and I have a macro to refresh the data. I want the macro to first check that the ODBC connection exists before trying to refresh the data. So it would look like:

IF ODBC Connection exists THEN refresh data ELSE return warning message.

becoz when connection cannot be made, its gives me error. and i have to manually press ok button.

Any ideas….?

thanks

View Answers


How To Fix ‘-2147467259 (80004005)’: [microsoft] [odbc Microsoft Access Driver] Not A Valid Password. — Excel

Adding records to Database getting following error…
Getting error message exact as below

Code:

 '-2147467259 (80004005)': [Microsoft]  
 [ODBC Microsoft Access driver] not a valid password  

Actual Code: error on BLUE line below.

I would really appriciate any help. Just stucked just dont know how to proceed…just same error already asked by someone too but doesnt solve me problem.

Code:

 Sub CallAddTransfer() 
   ' Used to call the code from page 480 
   Dim WS As Worksheet 
   Dim Qty As Integer 
   Set WS = Worksheets("AddRecords") 
   FinalRow = WS.Cells(Rows.Count, 1).End(xlUp).Row 
   Ctr = 0 
   For i = 7 To FinalRow 
       Style = Cells(i, 1).Value 
       FromStore = Cells(i, 2).Value 
       ToStore = Cells(i, 3).Value 
       Qty = Cells(i, 4).Value 
       Ctr = Ctr + 1 
       Application.StatusBar = "Adding Record " & Ctr 
       AddTransfer Style, FromStore, ToStore, Qty 
   Next i 
   Application.StatusBar = False 
   MsgBox Ctr & " records added." 
 End Sub 
 Sub AddTransfer(Style As Variant, FromStore As Variant, ToStore As Variant, Qty As Integer) 
   ' Page 480 
   Dim cnn As ADODB.Connection 
   Dim rst As ADODB.Recordset 
   Dim pwd As String 
 
   MyConn = ThisWorkbook.Path & Application.PathSeparator & "Transfers.mdb" 
   MyConn = "Driver=Microsoft Access Driver (*.mdb);DBQ=" & MyConn 
   pwd = "mypass" 
 
 
   ' open the connection 
   Set cnn = New ADODB.Connection 
   With cnn 
       '.Provider = "Microsoft.Jet.OLEDB.4.0" 
        .Open MyConn, mypass  
   End With 
 
   ' Define the Recordset 
   Set rst = New ADODB.Recordset 
   rst.CursorLocation = adUseServer 
 
   ' open the table 
   rst.Open Source:="tblTransfer", _ 
   ActiveConnection:=cnn, _ 
   CursorType:=adOpenDynamic, _ 
   LockType:=adLockOptimistic, _ 
   Options:=adCmdTable 
 
   ' Add a record 
   rst.AddNew 
 
   ' Set up the values for the fields. The first four fields 
   ' are passed from the calling userform. The date field 
   ' is filled with the current date. 
   rst("Style") = Style 
   rst("FromStore") = FromStore 
   rst("ToStore") = ToStore 
   rst("Qty") = Qty 
   rst("tDate") = Date 
   rst("Sent") = False 
   rst("Receive") = False 
 
   ' Write the values to this record 
   rst.Update 
 
   ' Close 
   rst.Close 
   cnn.Close 
 End Sub 

The code is from Bill’s Latest book i guess .

Thanks again

View Answers


Populate Combobox From Odbc Sql Query? — Excel

Hello,

Wondering if is it possible to populate a combobox with values from a single column sql query.

1: I do not want to have the recordset returned to a query table and then have combobox populate from query table (trying to cut out the «middleman»)
2: I have odbc connections only, I do not have the privledges to add on the ADO add-ons, and if I can get it, my clients will not have it.

so,
The connectionstring I use is this

Code:

Dim varconnection As String
        varconnection = "ODBC;DRIVER={SQL Server};Server=MyServer;DATABASE=MyDatabase;UID=that dude;PWD=password"

Any help would be greatly appreciated

View Answers


Vba To Connect To Database Using Odbc Data Source — Excel

I like to connect to a SQL 2005 database from my Excel VBA project.

I have setup a ODBC data source called MSSQLDEV that connects to the SQL 2005 database

How do I build the connection string using this ODBC data source to connect to the SQL 2005?
thanks.

View Answers


Vba: Using Querytables.add And Odbc To Query Mysql. Problem: Not All Columns Are Being Returned In Excel! — Excel

Alright, I’ve setup a little macro in excel based on VBA code which runs a query against a MySQL database. This setup has been working great for us without any problems until now.

It seems the SQL query I’m trying to run is breaking QueryTables somehow. This query I’m trying to run is complex and involves a «UNION ALL». This SQL query runs perfectly fine in MySQL Query Browser.

However, when I try and run this query using QueryTables.Add and ODBC, some of the columns are not being returned.

Specifically, I have found that the only columns not being returned are ones which do not have matching UNION «Field Types».

aka: On the top part of my UNION, the first column returned is an INT, and on the bottom of my UNION (the second query), the first column is a VARCHAR. For some reason MySQL Query Browser is perfectly okay showing these results, but QueryTables can’t handle it, and drops these columns.

ANY help would be VERY APPRECIATED!!

Here is my VBA code:

Code:

Sub SQLGetNewData()

Dim sConn As String
Dim sSql As String
Dim sDateFrom As String
Dim sDateTo As String
Dim oQt As QueryTable

'Sets the database connection
sConn = "ODBC;DSN=Database_Name;UID=username;PWD=password"

'get query parameters
Worksheets("Data").Activate

'build the query.
' I have not included the original complex SQL query here, and I have created a "VIEW" in MySQL to replicate the query. Because I have created a VIEW, I simply need to query this view just like it's a table.

sSql = "SELECT * from view_revenue "


Worksheets("Query Info").Activate
[B7].Formula = sSql

'clear the data area
Worksheets("Data").Activate
Range("a1").CurrentRegion.ClearContents

'clear existing data connections
For Each oQt In ActiveSheet.QueryTables
    oQt.Delete
Next oQt
If ActiveWorkbook.Connections.Count > 0 Then
    i = 1
    Do While ActiveWorkbook.Connections.Count > 0
        ActiveWorkbook.Connections.Item(i).Delete
        i = i - 1
    Loop
End If



'get new data
With ActiveSheet.QueryTables.Add(Connection:=sConn, _
        Destination:=Range("A1"), Sql:=sSql)
    .Refresh BackgroundQuery:=False
    .RefreshPeriod = 0
    .RefreshOnFileOpen = False
    
End With


Worksheets("Data").Activate

End Sub

View Answers


Vba To Get Database Name From An Established Odbc Connection? — Excel

Ok, here is the issue…

I’ve written an add-in that is used in a couple of locations. In each location, users have an ODBC connection to a database. The name of that ODBC connection is the same at each location.

However, the name of the actual database that it connects to varies…

For instance, in one location it is «Database»

But in another location it is «DATABASE»

The database holds the same information at both locations, but I’ve found my queries are case sensitive when it comes to establishing a connection.

Right now, I’m getting around it by using an inputbox, bt there has to be a better way…

Is there any way to use VBA to look at an existing ODBC connection and then get the name of the DB from there?

Any help or advice is appreciated.

View Answers


Odbc Microsoft Access Driver Login Failed — Excel

Hi,

A query has landed on my desk — which i’m struggling to figure out.

I have an Excel 2007 workbook which pulls data from a shared Access database.

The user has complained that it is not working properly.

To test it I attempted to refresh the connections, and get an error message:

ODBC Microsoft Access Driver Login Failed

Which then continues to say that it cannot find the mdb file. However, the path that it states the file should be in is different to where it is. This was working fine yesterday.

We also had a mandatory service update overnight — would this potentially cause this?

I’m trying to figure out if the file has been moved, whether it is a problem with the ODBC setup (and therefore infrastructure can have a look), or whether I have inadvertently changed something within the database itself (although I have only been creating queries).

Any help would be much appreciated!

pinkshirt

View Answers


Odbc / Shared File On A Network Question — Excel

I have a file on a netowk that has an ODBC sql feed set up.

When I choose to share the file, the «REFRESH DATA» icon is shaded out — thus meaning the user can not refresh on demand.

Im using excel 2003 is there a route round this?

View Answers


Set Up Odbc Datasource Via Vba If User Doesn’t Have It Already — Excel

Hello All,

I have a query table that is refreshed from a sql server. I have the connection string figured out

Code:

ODBC;
DSN=myDSN;
Description=myDescription;
DATABASE=mydatabase;
UID=me;
PWD=mypassword

but, when I try to use it on someone’s computer who doesn’t have a datasource setup, it prompts them to do so with the ODBC Administrator program. Is there a way I can do this programatically?

user’s connection is to a SQL database.

Update: Okay, found out about DSN-less connections currently using

Code:

varConnection = "ODBC;DRIVER={SQL Server};Server=myserver;DATABASE=mydatabase;UID=me;PWD=mypassword"

However, the «Select Datasource» window still crops up. How do I set up the connect to avoid any prompts to «select Datasource» as that is a manual, technical process

Update: for servername, had to specify ip address as some end users were accessing remotely.

View Answers


Multiple Sql Statements Off One Odbc Connection — Excel

Hello,

I was wondering if it was possible to have more than one SQL statement off one ODBC Connection?

And if the answer is ‘Yes’ how?

Many Thanks

Andy

View Answers


Run-time Error 3146 Odbc —call Failed — Excel

I’m working with this Access 2000 database and am trying to export some information but continue to get the following error after I select the location to save…

Run-time error 3146 ODBC —call failed
When I attempt to debug the error it’s high-lighting the following code…

DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel8, «TargSO», strFolderName & («Open_Sales») & Format(Date, «yymmdd») & «-» & Format(Time, «hhnn») & «.xls», True
MsgBox («File Created!»)

could anyone shed some light on whats going on or point me in the right direction?

any help would be muchly appreciated — thanks in advance.

View Answers


Odbc Connection To Oracle — Prompting For Server Name — Excel

Hi Folks:

I have a VBA script that communicates with Oracle — when I click on the refresh button, a dialog box pops up and asks for the Server Name …. I was wondering if I can pass this variable to the connection instead of having the users have to enter it each time — the problem is that they likely don’t even know what the server name is.

Thanks

Don

Query is below:

If global_username = «» Then Call password_entry

strConOracle = «Driver={Microsoft ODBC for Oracle}; CONNECTSTRING=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP) «
strConOracle = strConOracle & «(HOST=» & HOST & «)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=» & DBNAME
strConOracle = strConOracle & » ))); uid=» & ORACLE_USER_NAME & » ;pwd=» & ORACLE_PASSWORD & «;»

Set oConOracle = CreateObject(«ADODB.Connection»)
qstr = » Select * from query_result «

oConOracle.Open strConOracle

splitsql = SplitString(qstr)

‘ On Error Resume Next

With ActiveWorkbook.PivotCaches.Add(SourceType:=xlExternal)
.Connection = «OLEDB;» & oConOracle
.CommandType = xlCmdSql
.CommandText = splitsql
.CreatePivotTable TableDestination:= _
«‘[ABCHAMP_resp_prof_JUL10 v17.xls]MainMenu’!R23C3″, TableName:=»PivotTable1», _
DefaultVersion:=xlPivotTableVersion10
End With

View Answers


Macro To Change Odbc Connection Settings — Excel

Running the macro recorder I got this:

Code:

With ActiveWorkbook.Connections("YearBS").ODBCConnection
.BackgroundQuery = False
.CommandText = Array( _
"sp_report BalanceSheetStandard show Label, Amount parameters DateFrom = {d'2009-01-01'}, DateTo = {d'2010-12-31'}, " _
, "SummarizeColumnsBy = 'Month'")
.CommandType = xlCmdSql
.Connection = Array(Array( _
"ODBC;DSN=QuickBooks Data;DFQ=I:ACCOUNTINGtest.QBW;SERVER=QODBC;OptimizerDBFolder=%UserProfile%QODBC " _
), Array( _
"Driver for QuickBooksOptimizer;OptimizerAllowDirtyReads=N;SyncFromOtherTables=N" _
))
.RefreshOnFileOpen = False
.SavePassword = False
.SourceConnectionFile = ""
.ServerCredentialsMethod = xlCredentialsMethodIntegrated
.AlwaysUseConnectionFile = False
End With

Now I want the 2 YEARS to be able to change based on cell data… Or if it helps the 2 cells are just This Year and last year (ie. NOW() and NOW()-365 but formatted as custom = YYYY)

So I have this, but it seems to throw me an error everytime I try it:

Code:

 With ActiveWorkbook.Connections("YearBS").ODBCConnection
        .BackgroundQuery = False
        .CommandText = Array("sp_report BalanceSheetStandard show Label, Amount parameters DateFrom = {d'" + Range("D7").Text + "-01-01'}, DateTo = {d'" + Range("D8").Text + "-12-31'}, SummarizeColumnsBy = 'Month'")
        .CommandType = xlCmdSql
        .Connection = Array(Array( _
        "ODBC;DSN=QuickBooks Data;DFQ=I:ACCOUNTINGtest.QBW;SERVER=QODBC;OptimizerDBFolder=%UserProfile%QODBC " _
        ), Array( _
        "Driver for QuickBooksOptimizer;OptimizerAllowDirtyReads=N;SyncFromOtherTables=N" _
        ))
        .RefreshOnFileOpen = False
        .SavePassword = False
        .SourceConnectionFile = ""
        .ServerCredentialsMethod = xlCredentialsMethodIntegrated
        .AlwaysUseConnectionFile = False
    End With

The error I get now in Microsoft VB is

Run-time error ‘1004’:
Application-defined or object-defined error

I also tried changing

Code:

.CommandText = Array("sp_report BalanceSheetStandard show Label, Amount parameters DateFrom = {d'" + Range("D7").Text + "-01-01'}, DateTo = {d'" + Range("D8").Text + "-12-31'}, SummarizeColumnsBy = 'Month'")

to

Code:

.CommandText = Array( GetSQLString() )

after making

Code:

Public Function GetSQLString()
    GetSQLString = "sp_report BalanceSheetStandard show Label, Amount parameters DateFrom = {d'" + Range("D7").Text + "-01-01'}, DateTo = {d'" + Range("D8").Text + "-12-31'}, SummarizeColumnsBy = 'Month'"
End Function

I also tried

Code:

.CommandText = Array(Sheet3.Range(D10))

after setting D10 on sheet3 to =GetSQLString()

Thanks for your help!

View Answers


How To Test Odbc Connection — Excel

I have created a system DSN to an SQL Database programmatically and would like to test the database connection via a command button before executing any queries against the database.

Can anyone help me write this?

View Answers


Odbc Connection To Ms Project — Excel

I need to create a database query within execl so I can update my excel sheet directly from a ms project source file.

Background story — currently have a massive programme plan. We also have an excel sheet which contains an extract of all the milestones from the programme plan. The excel sheet is updated on a weekly basis — updates made on RAG status, milestone end date and % complete. We are using a ‘milestone code’ to reference from excel to project. Because its a manual process of checking each individual milestone in the programme plan (140 milestones) its a long and tiresome process.

I was thinking that if we could automate this using an ODBC connection so it updates the data automatically it would cut down an hours work to the click of a button. So basically I was just wanting to know if that is possible. If not, are there any other suggestions to update the information automatically.

Thanks in advance.

P.S. I have attached a picture of a sample spreadsheet and project file as a reference. Hopefully it should give people an idea of what they look like and what Im trying to achieve.

View Answers


Vba To Modify Existing Odbc Data Source — Excel — Excel

Alright I have an existing data connection to an ODBC data source. I am curious how I can modify one of the query parameters programatically.

So for instance, my data connection properties which already has a connection setup includes this statement.statement:

SELECT «DataTable».»User Name»
FROM «DataTable» «DataTable»
WHERE («DataTable».»Office Location»= ‘Dallas TX’)

And I can refresh this query via VBA with Activeworkbook.RefreshAll or something similiar.

My question is, is there any way to programmatically change the queries parameter on the fly?

So I would like to define a variable called «Location» and then insert that into the Office Location part of the query…

I think if someone could help me get my data connection completely into VBA, instead of on the Data Connections tab, I could probably figure it out myself.

Thanks!

View Answers


Odbc Connection To Sql Server With Excel — Excel

Hi

We regularly develop queries from Excel via MS query to an SQL Server 2005 database.

We have had issues where if an Alias is used in the SQl Database and the Alias contains spaces MS query complains to the effect ‘Incorrect syntax near «whatever». On replacing the spaces with underscores all is well. Now to the point, we developed a spreadsheet using the above connections (even having the alias with spaces) and all was fine. It has now decided to erratically complain with ‘incorrect syntax etc.» message. Sometimes it will run correctly on my collegues machine but wont run correctly on mine. Strangley enough the client can dial in remotley and run the query fine.

We have SQL server 2005 and excel 2003 and 2007 and run windows xp professional.

Has anyone had this one before?

Regards

Alan

View Answers


Odbc Query With Current Date — Excel

I am trying to pull data into excel from another program using the ODBC query. This is the code that i have:

WHERE («BV:CallTracker».»Create-date»>={ts ‘2010-07-05 00:00:00’ })

where the date is located is what I am trying to change. I need it to just pull the current date without me having to manually enter it in.

View Answers


Change Odbc Connection In Excel Vba — Excel

Hi,

I have this connection which is working fine now. But i like it to be dynamic and picking up the new range from excel. I tried changing the cells in red to fPath but it wouldn’t work.

Hope someone can enlighten. Thanks.

Currently, cell E3 read as: C:DATADEMO17_DB.mdb

Sub SQLQuery()

Dim varConnection
Dim varSQL
Dim fPath As String

fPath = Range(«E3»).Value

Range(«A1»).CurrentRegion.ClearContents

varConnection = «ODBC; DSN=MS Access Database; DBQ= C:DATADEMO17_DB.mdb ; Driver{Driver do Microsoft Access(*.mdb)}»

varSQL = «SELECT DISTINCT AGENT from AGENTNAME»

With ActiveSheet.QueryTables.Add(Connection:=varConnection, Destination:=ActiveSheet.Range(«A1»))
.CommandText = varSQL
.Refresh BackgroundQuery:=False
End With

End Sub

View Answers


Vba Macro To Refresh Odbc Connection Only Works Once — Excel

Hello all,

I’m trying to use a macro to refresh a pivot table obtained thru an ODBC connection. At the same time, i want to change the CommandText field to change the dates i’m using (I only want to get one year of data). I did this by recording the refresh and then changing the CommandText. Here is the code I have at the moment:

Code:

    FullString = "V_DATE_ACT>={ts '" + Dinicio + " 00:00:00'}) AND (V_LOGONE_DB.DLV_DATE_ACT

View Answers


Broken Odbc Links Within Excel — Excel

I have a client that has hundreds of spreadsheets that use database queries created within excel (not vb) to link to data stored in a third-party database (Pervasive) via ODBC.

Recently that datbase moved from Drive D: to Drive E:. I updated the ODBC connection to reflect the move. Unfortunately, now none of the excel queries work. I get an ODBC connection error.

If I create a brand new query using the same DSN, it works fine. The DSN also works fine in Access and Word.

I guess when the query is stored in Excel, it stores the the data location within the spreadsheet and no longer references the DSN. Is there any way to view or modify this connection short of creating new queries in hundreds of spreadsheets.

Thanks

View Answers


Connect To Oracle Via Odbc Without Any Dialog For Password — Excel

Hi,
I have the same problem!!!

http://www.excelforum.com/excel-programming/610563-macro-to-automatically-hit-database-using-password.html

Does anyone no this?

View Answers


Excel Odbc — Excel

Hi,

I am using Excel 2007 and Tally 9. I was able to export some master data from Tally into excel using ODBC but am unable to export transactions data

I someone could help me would really appreciate it

View Answers


Increasing Activeworkbook.refreshall Performance For Odbc Connection…. — Excel

I have a spreadsheet that has over 30 ODBC queries to a MS Access database. Via VBA I programmed a command button to do a simple refresh all:

ActiveWorkbook.RefreshAll

This takes about 30 minutes to complete…it seems to take a long time to Connect to the datasource (based upon the status bar message).

If I change the code to have 30 entries of the code below it takes less than 1 minute:

Worksheets(«Sheetx»).Activate
‘A1 is the location of the query table
Worksheets(«Sheetx»).Range(«A1»).Select
Selection.QueryTable.Refresh BackgroundQuery:=False

The workaround is worth it from a performance perspective but NOT from a maintenance perspective. Any advice on how to make the ActiveWorkbook.RefreshAll run in a reasonable amount of time.

View Answers


General Odbc Error — Run Time Error 1004 — Excel

Please help me before this laptop becomes a Frisbee!

I almost have this working but I’m getting stuck on this error every time I execute it. I have an ODBC with read-only privileges and I recorded part of the code from the macro. The «from» and «to» date fields I added ( I think I’m correct). I would truly appreciate the help.

Here’s the code:

Private Sub CommandButton1_Click()
Dim smpldatea As Date
Dim smpldateb As Date

Dim fdate1 As String
Dim fdate2 As String

smpldatea = UserForm1.TextBox1.Text
smpldateb = UserForm1.TextBox2.Text

fdate1 = Format(smpldatea, «m/d/yyyy hh:mm:ss»)
fdate2 = Format(smpldateb, «m/d/yyyy hh:mm:ss»)

Sheets(«Sheet1»).Activate

Range(«A1:H10000»).ClearContents

With ActiveSheet.QueryTables.Add(Connection:=Array(Array( _
«ODBC;DRIVER={Oracle in OraHome92};SERVER=XXXXXX;UID=DT_I;PWD=RO2ACCESS;DBQ=XXXXXXP;DBA=W;APA=T;EXC=F;XSM=Default;FEN=T;QTO=T;FRC=10» _
), Array( _
«;FDL=10;LOB=T;RST=T;GDE=F;FRL=Lo;BAM=IfAllSuccessful;MTS=F;MDI=Me;CSR=F;FWC=F;PFC=10;TLO=O;» _
)), Destination:=Range(«A1»))
.CommandText = Array( _
«SELECT DT_CENTERLINE_AUDIT.AUDIT_DATE, DT_CENTERLINE_AUDIT.CENTERLINE_ID, DT_CENTERLINE_AUDIT.COMPLIANT, DT_CENTERLINE_AUDIT.CORRECTED, DT_CENTERLINE_AUDIT.LINE, DT_CENTERLINE_AUDIT.LOCATION» & Chr(13) & «» & Chr(10) & «FROM DTD» _
, _
«BA.DT_CENTERLINE_AUDIT DT_CENTERLINE_AUDIT» & Chr(13) & «» & Chr(10) & «WHERE (DT_CENTERLINE_AUDIT.AUDIT_DATE>= ‘» & fdate1 & «‘ And DT_CENTERLINE_AUDIT.AUDIT_DATE

View Answers


Automating Ado/odbc Connection — Excel

I have a client with an excel spreadsheet that is based on several ODBC queries. He is writing a macro to automate the data refresh. He has the username/password for the server coded in the connection string as described on Microsoft’s support site: «DSN=; UID=; PWD=
;» and the password is saved in the ODBC connection as well. However, when he runs the Macro to refresh, it still prompts him for the password as it refreshes each query. The username populates correctly but the password field stays blank. Any ideas?

View Answers


Odbc Connection Error — Excel

Hello,

I am modifying the macro in Excel, which was written by my colleague before he quits the company. I have been assigned to continue coding the macro in Excel. The objective of this macro would be » get the required data from a local DB by calling the SQL query and plot the graph based on the data gathered » .

I am quite new to this environment and I am slowly learning the VBA scripts coded by my colleague. When I run the macro, I am getting the Run time error

«Run Time Error 3146 ODBC — call failed». I searched in the internet to resolve this problem, but I couldn’t. May be if I am aware of those kind of Excel macros, I could have solved this run time error.

I have pasted below the code

Public FileContents As String ‘global variable to contain the SQL query string
Public RowCounter As Integer
Public ColCounter As Integer
Public RowCounter1 As Integer
Public ColCounter1 As Integer
Const FTP_ip = «10.68.20.158»

Private Sub CommandButton1_Click()

Dim strDBName As String
Dim strDBUser As String
Dim strDBPwd As String
Dim strDSNName As String
Dim strConnectionStr As String
Dim strQueryFile_path As String ‘filepath of SQL Query file
Dim wrkODBC As Workspace
Dim conDb As Connection
Dim rstTemp As Recordset

strDBName = «tpfdb»
strDBUser = «root»
strDBPwd = «admin»
strDSNName = «tpfdatabase»
strQueryFile_path = ThisWorkbook.Path & «Queries»

‘ Create ODBCDirect Workspace object.
Set wrkODBC = CreateWorkspace(«NewODBCWorkspace», strDBUser, strDBPwd, dbUseODBC)

‘ Open read-only Connection object based on information
‘ you enter in the ODBC Driver Manager dialog box.
strConnectionStr = «ODBC;DATABASE=» + strDBName + «;UID=» + strDBUser + «;PWD=» + strDBPwd + «;DSN=» + strDSNName
Set conDb = wrkODBC.OpenConnection(«localdb», dbDriverComplete, False, strConnectionStr)
Set rstTemp = conDb.OpenRecordset(«SET GLOBAL sql_mode=’ANSI’;», dbOpenDynamic)

I am getting the error while executing the command highlighted above. As I said i am new to this environment, can anyone help me to resolve this?

Also it would be great if anyone can give me some reference/websites that tells about ODBC in Excel.

Many Thanks in Advance!!!!!!!!!!

———————————————————-

Regards,

Hari.

View Answers


Excel Odbc Connection To Sql Server Table Failed — Excel

Programmers,

Here is the situation: The company I work for has several Excel spreadsheets that are linked to our SQL Server 2000 database via an Access file. All has worked for years until now. When I try to Refresh the spreadsheet for Company3, I get an ODBC Connection Failed Error. Basically, the configuration is as follows:

SQL Server: Database has 3 tables for each company which we will call respectively — Company1, Company2, Company3.

AccessFile.mdb contains linked tables to those tables.

Excel Spreadsheets have a Microsoft Query defined using a Microsoft Access ODBC driver. From there, the linked table
Company3 and its appropriate columns are selected. (it is interesting to note the connection seems to work as it will show the column names when I click (+) to expand the table.) However, as soon I try to run the query, it fails with a ODBC Connection Error.

+++ Note +++ If I select a SQL Server ODBC driver instead of a Microsoft Access ODBC driver in the Microsoft Query Wizard, it will work fine. Data gets refreshed with no problem.

Here is what I have tried and observed:

1. Tested the OBDC connection through the ODBC Datasource Adminstrator. Works fine.

2. In Microsoft Query, selected SQL Server 2000 ODBC Driver.
Refreshed the Excel Spreadsheet. Works as mentioned above.
(The current configuration worked previously using an Access ODBC Driver to the linked SQL table.)

3. Created a new Access database with a link to Company3, thinking maybe the mdb file is corrupt. Still didn’t work.

4. I created a new Excel spreadsheet and Microsoft Query to
to the linked table. Same results.

5. Compared the datatypes for Company3 against Company1 and Company2. Looked ok.

6. Copied Company3 into a test table. Tried Refreshing the Excel spreadsheet with Access ODBC Driver and the test table (all records). ODBC Connection failed. I even tried deleting all but one record in the table, but I obtained the same results.

7. Tried SQL Profiler to see if could give any useful information why the conncection failed. All I could find that it was testing the connection, but I could find any information why it failed.

9. Turned on ODBC tracing. Here is a snapshot of the log file:

msqry32 580-eb0 ENTER SQLDriverConnectW
HDBC 00892BD0
HWND 00000000
WCHAR * 0x74329A38 [ -3] «****** 0»
SWORD -3
WCHAR * 0x74329A38
SWORD 2
SWORD * 0x00000000
UWORD 3 <SQL_DRIVER_COMPLETE_REQUIRED>

msqry32 580-eb0 EXIT SQLDriverConnectW with return code -1 (SQL_ERROR)
HDBC 00892BD0
HWND 00000000
WCHAR * 0x74329A38 [ -3] «****** 0»
SWORD -3
WCHAR * 0x74329A38
SWORD 2
SWORD * 0x00000000
UWORD 3 <SQL_DRIVER_COMPLETE_REQUIRED>

DIAG [IM006] [Microsoft][ODBC Driver Manager] Driver’s SQLSetConnectAttr failed (0)

DIAG [IM008] [Microsoft][ODBC SQL Server Driver]Dialog failed (0)

msqry32 580-eb0 ENTER SQLErrorW
HENV 00892B58
HDBC 00892BD0
HSTMT 00000000
WCHAR * 0x0012D488 (NYI)
SDWORD * 0x0012D4D4
WCHAR * 0x02417260
SWORD 4095
SWORD * 0x0012D4C0

msqry32 580-eb0 EXIT SQLErrorW with return code 0 (SQL_SUCCESS)
HENV 00892B58
HDBC 00892BD0
HSTMT 00000000
WCHAR * 0x0012D488 (NYI)
SDWORD * 0x0012D4D4 (0)
WCHAR * 0x02417260 [ 66] «[Microsoft][ODBC Driver Manager] Driver’s SQLSetConnectAttr failed»
SWORD 4095
SWORD * 0x0012D4C0 (66)

msqry32 580-eb0 ENTER SQLErrorW
HENV 00892B58
HDBC 00892BD0
HSTMT 00000000
WCHAR * 0x0012D488 (NYI)
SDWORD * 0x0012D4D4
WCHAR * 0x024172F6
SWORD 4020
SWORD * 0x0012D4C0

msqry32 580-eb0 EXIT SQLErrorW with return code 0 (SQL_SUCCESS)
HENV 00892B58
HDBC 00892BD0
HSTMT 00000000
WCHAR * 0x0012D488 (NYI)
SDWORD * 0x0012D4D4 (0)
WCHAR * 0x024172F6 [ 48] «[Microsoft][ODBC SQL Server Driver]Dialog failed»
SWORD 4020
SWORD * 0x0012D4C0 (48)

msqry32 580-eb0 ENTER SQLErrorW
HENV 00892B58
HDBC 00892BD0
HSTMT 00000000
WCHAR * 0x0012D488 (NYI)
SDWORD * 0x0012D4D4
WCHAR * 0x02417368
SWORD 3963
SWORD * 0x0012D4C0

msqry32 580-eb0 EXIT SQLErrorW with return code 100 (SQL_NO_DATA_FOUND)
HENV 00892B58
HDBC 00892BD0
HSTMT 00000000
WCHAR * 0x0012D488 (NYI)
SDWORD * 0x0012D4D4
WCHAR * 0x02417368
SWORD 3963
SWORD * 0x0012D4C0

msqry32 580-eb0 ENTER SQLFreeConnect
HDBC 00892BD0

msqry32 580-eb0 EXIT SQLFreeConnect with return code 0 (SQL_SUCCESS)
HDBC 00892BD0

msqry32 580-eb0 EXIT SQLExecute with return code -1 (SQL_ERROR)
HSTMT 00891B18

DIAG [S1000] [Microsoft][ODBC Microsoft Access Driver] ODBC—connection to ‘CompanyDatabase’ failed. (-2001)

Not sure what is causing this error. I am leaning that it has to so some thing with the table (Company3) itself. Permissions? Any assistance on issue would be greatly appreciated.:-)

By the way, does anyone know why sometimes you get a login dialog when you open a datasource and sometimes not?

View Answers


Odbc Connect Via Macro — Excel

I wish to import a Oracle table via a macro and have done it via the wizzard and recorded that. when i run it i get a 1004 error at the refresh. I then scripted it myself and it fails at the connect line. Can you help me please. I got the driver from a record macro script…

My script:

Dim oConn As Object, oRS As Object
Password = InputBox(«input password», «enter password»)
Set oConn = CreateObject(«ADODB.Connection»)
oConn.Open «Driver={Oracle ODBC Driver};» & _
«Dbq=RPTCCB;» & _
«Uid=JSHAPER;» & _
«Pwd=» & Password

Set oRS = CreateObject(«ADODB.RecordSet»)
oRS.Open «SELECT SC_ACCESS_CNTL.USR_GRP_ID, SC_ACCESS_CNTL.APP_SVC_ID, SC_ACCESS_CNTL.ACCESS_MODE, SC_USR_GRP_PROF.EXPIRATION_DT, SC_ACCESS_CNTL.VERSION, SC_ACCESS_CNTL.OWNER_FLG FROM CRYSTAL.SC_ACCESS_CNTL SC_ACCESS_CNTL, PRDCCB01.SC_USR_GRP_PROF SC_USR_GRP_PROF WHERE SC_ACCESS_CNTL.APP_SVC_ID = SC_USR_GRP_PROF.APP_SVC_ID AND SC_ACCESS_CNTL.USR_GRP_ID = SC_USR_GRP_PROF.USR_GRP_ID», oConn

Range(«A1»).CopyFromRecordset oRS

Thank you in advance to anyone that spends any time helping me figure this out…

View Answers


Sql Query (odbc) With Cell Reference — Excel

I have a SQL query (through an ODBC connection) that populates an Excel spreadsheet. The thing is that I want add a criteria «WHERE x = [cell reference]». I know this question has been asked repeatedly in different forms but it seems that connecting with Excel 2007 through an ODBC connection doesn’t behave the way others do. I’ve tried using the following syntax:

WHERE A.EMPLID = ‘» & Range(«B1») & «‘

A.EMPLID is my SQL field name
B1 is the cell where I enter my A.EMPLID filter value

If I manually edit the query (as below) it returns a perfect set of data. I’m just trying to avoid having to manually edit the query every time I want a new data set.

WHERE A.EMPLID = ‘81726354’

The query with the cell reference doesn’t cause any errors but it doesn’t return any results either. I’ve also named the cell as a range but don’t know how I’d reference that in a SQL query (if that’s even possible). I’m trying to avoid doing it with VBA.

View Answers


What Does This Mean? : Microsoft Odbc Access Driver Too Few Parameters Expected 1 — Excel

I have had this message pop up on a workbook that has been running flawlessly for monthe. The table goes to an Access book and queries a table and imports the reuslts. And suddenly today I am getting this message. Does anyone know what it means?

[Microsoft] [ODBC Access Driver] Too few parameters: Expected 1

View Answers


Vba Code For Getting Data From Oracle — No Odbc — Excel

Hi All,

I need your help. Could you please provide me a sample code which will allow me to connect to Oracle 10g Database and get some rows out of it. I want to do it without using ODBC

Thanks
Yeheya

View Answers


Macro To Change Odbc Connection String — Excel

I am trying to change the SQL command to an odbc database connection

Code:

Sub Macro1()
'
' Macro1 Macro
'
'
    With ActiveWorkbook.Connections("YearBS").ODBCConnection
        .BackgroundQuery = False
        .CommandText = Array( _
        "sp_report BalanceSheetStandard show Label, Amount parameters DateFrom = {d'2009-01-01'}, DateTo = {d'2010-12-31'}, " _
        , "SummarizeColumnsBy = 'Month'")
        .CommandType = xlCmdSql
        .Connection = Array(Array( _
        "ODBC;DSN=QuickBooks Data;DFQ=I:ACCOUNTINGQuickbooksRed Tail Networks, Inc.QBW;SERVER=QODBC;OptimizerDBFolder=%UserProfile%QODBC " _
        ), Array( _
        "Driver for QuickBooksOptimizer;OptimizerAllowDirtyReads=N;SyncFromOtherTables=N" _
        ))
        .RefreshOnFileOpen = False
        .SavePassword = False
        .SourceConnectionFile = ""
        .ServerCredentialsMethod = xlCredentialsMethodIntegrated
        .AlwaysUseConnectionFile = False
    End With
    With ActiveWorkbook.Connections("YearBS")
        .Name = "YearBS"
        .Description = ""
    End With
    ActiveWorkbook.Connections("YearBS").Refresh
End Sub

I recorded that in excel and then when I try to run it I get an error of:
When I debug it highlights this line:

Code:

        .CommandText = Array( _
        "sp_report BalanceSheetStandard show Label, Amount parameters DateFrom = {d'2009-01-01'}, DateTo = {d'2010-12-31'}, " _
        , "SummarizeColumnsBy = 'Month'")

Any help would be appreciated thank you.

Now I also found this:
http://p2p.wrox.com/excel-vba/29037-…has-1-rpt.html

which makes it out to be a bug in excel and that I need to change the type of connection, then change the string, then change the type of connection back. I am not really sure how to do this but below is the post that seems important from the link above:

Quote:

I wrote the following functions which I call right before and after I update the CommandText.

Private Sub dbODBCtoOLEDB()
Dim pcPivotCache As PivotCache
Dim strConnection As String
For Each pcPivotCache In ActiveWorkbook.PivotCaches
If pcPivotCache.QueryType = xlODBCQuery Then
strConnection = _
Replace(pcPivotCache.Connection, «ODBC;DSN», «OLEDB;DSN», 1, 1, vbTextCompare)
pcPivotCache.Connection = strConnection
End If
Next pcPivotCache
End Sub

Private Sub dbOLEDBtoODBC()
Dim pcPivotCache As PivotCache
Dim strConnection As String
For Each pcPivotCache In ActiveWorkbook.PivotCaches
If pcPivotCache.QueryType = xlOLEDBQuery Then
strConnection = _
Replace(pcPivotCache.Connection, «OLEDB;DSN», «ODBC;DSN», 1, 1, vbTextCompare)
pcPivotCache.Connection = strConnection
End If
pcPivotCache.Refresh
Next pcPivotCache
End Sub

If anyone could help me adapt this to my connection that would be incredible. It is important to note I will be running this 3 times to change seperate pivot tables and that I also have other pivot tables that connect to a different database that I do not need changed. Thanks!

View Answers


Using Function In In Access Odbc Query — Excel

Hey Guys,

I have an access database as a store for some data. I have a custom function in my MDB that is basically a CASE statement. It works when build queries within the MDB itself…is there a way I can call on this function when querying the tables externally via an access ODBC connection?

I am using microsoft query to pull the data into excel.

Thanks

View Answers


Odbc —call Failed — Struggling With This For Weeks — Excel

Hi,

I just started working with access and I am getting this error every two queries that I run. What I need to do is close Access and start it again and then I get to run two more queries and it crashes again.

I dont know why this is happening but obviously something it wrong. I Googled it and could not find an answer.

The error message I get is:

ODBC—call failed.
[MySQL][ODBC 5.1 Driver]….-highperf-b13-log]MySQL server has gone away (#2006)

Does anyone know why this is happening and what I can do to fix it?

Please let me know.

Thanks,
— Lior

View Answers


Column Limit Using Excel To Excel Odbc — Excel

Currently I have an excel 2007 spreadheeet with around 400 columns of data, I was then hoping to make an ODBC connection to this from a worksheet on a second spreadsheet. Unfortunately only 250 odd columns are actually being recognised using this ODBC link, is there a way around this?

View Answers


Like this post? Please share to your friends:
  • Excel vba objects and methods
  • Excel vba items in combobox
  • Excel vba object module
  • Excel vba isnumber vba
  • Excel vba is value in array