Excel reads database tables and excel reads Databases

Source: Internet
Author: User

Excel reads database tables and excel reads Databases

The following code is used to read the table fields of a database using an Excel macro.

Public Sub getdata () Dim cnn As New ADODB. connection, sh As Worksheet Dim rs As New ADODB. recordset Dim cnnStr As String, SQL As String cnnStr = "Provider = SQLOLEDB; Initial Catalog = BI" & "; User ID = sa" & "; Password = Aa123456 "&"; data Source = 172.16.0.73 "cnn. connectionString = cnnStr cnn. open SQL = "SELECT * from dbo. tt "MsgBox": "& SQL Set rs = cnn. execute (SQL) For col = 0 To rs. fields. coun T-1 Sheets ("Sheet2 "). range ("A1 "). offset (0, col ). value = rs. fields (col ). name Next Sheets ("Sheet2 "). range ("A1 "). offset (1, 0 ). copyFromRecordset rs. close MsgBox "the query is finished! "Set rs = Nothing cnn. Close Set cnn = NothingEnd Sub

Code Description:
Data Source: Database IP Address
Catalog: Database Name
User ID: User Name
Password: Database Password
SQL: An SQL statement that reads a table directly.
The execution process has two pop-up windows. Click OK.
Finally, the data is written to the sheet 2 of the current Excel file.

To execute the above Code, you also need to set it for Excel:
It's probably a Library, but I cannot remember it. I will update this article later.

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.