sql >> Database >  >> RDS >> Sqlserver

Excel VBA gebruiken om SQL-query uit te voeren

Hieronder staat code die ik momenteel gebruik om gegevens van een MS SQL Server 2008 naar VBA te trekken. U moet ervoor zorgen dat u de juiste ADODB-referentie hebt [VBA Editor->Tools->Referenties ] en zorg ervoor dat u Microsoft ActiveX Data Objects 2.8 Library . hebt aangevinkt, de tweede van de onderste rij die is aangevinkt (ik gebruik Excel 2010 op Windows 7; je hebt misschien een iets andere ActiveX-versie, maar deze begint nog steeds met Microsoft ActiveX):

Submodule voor verbinding met MS SQL met externe host en gebruikersnaam/wachtwoord

Sub Download_Standard_BOM()
'Initializes variables
Dim cnn As New ADODB.Connection
Dim rst As New ADODB.Recordset
Dim ConnectionString As String
Dim StrQuery As String

'Setup the connection string for accessing MS SQL database
   'Make sure to change:
       '1: PASSWORD
       '2: USERNAME
       '3: REMOTE_IP_ADDRESS
       '4: DATABASE
    ConnectionString = "Provider=SQLOLEDB.1;Password=PASSWORD;Persist Security Info=True;User ID=USERNAME;Data Source=REMOTE_IP_ADDRESS;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Use Encryption for Data=False;Tag with column collation when possible=False;Initial Catalog=DATABASE"

    'Opens connection to the database
    cnn.Open ConnectionString
    'Timeout error in seconds for executing the entire query; this will run for 15 minutes before VBA timesout, but your database might timeout before this value
    cnn.CommandTimeout = 900

    'This is your actual MS SQL query that you need to run; you should check this query first using a more robust SQL editor (such as HeidiSQL) to ensure your query is valid
    StrQuery = "SELECT TOP 10 * FROM tbl_table"

    'Performs the actual query
    rst.Open StrQuery, cnn
    'Dumps all the results from the StrQuery into cell A2 of the first sheet in the active workbook
    Sheets(1).Range("A2").CopyFromRecordset rst
End Sub



  1. Kan geen verbinding maken met heroku postgresql-database vanuit de lokale node-app met sequelize

  2. ORA-00979 geen groep op uitdrukking

  3. Hoe te ontsnappen aan één citaat, speciale tekens in MySQL

  4. Configuratiesysteem kan niet worden geïnitialiseerd