2017-03-10 16 views
2

他のExcelブックからデータを取得するために、Excelでクエリを実行する接続文字列とSQLスクリプトを作成しようとしています。Excel VBAでSQLを使用して他のExcelブックにアクセス

Sub Test() 

    Dim conn As ADODB.Connection 
    Dim rs As ADODB.Recordset 
    Dim sConnString As String 
    Dim sql As String 

    ' Create the connection string. 
    sConnString = "provider=Microsoft.Jet.OLEDB.4.0;data source=" & _ 
       "C:\Users\dblois\Desktop\Shareenas Report.xlsx" + ";Extended Properties=Excel 8.0;" 

    ' Create the Connection and Recordset objects. 
    Set conn = New ADODB.Connection 
    Set rs = New ADODB.Recordset 

    sql = "SELECT * FROM [Data$A1:AC73333]" 

    ' Open the connection and execute. 
    conn.Open sConnString 
    Set rs = conn.Execute(sql) 

    ' Check we have data. 
    If Not rs.EOF Then 
     ' Transfer result. 
     Sheets(1).Range("A1").CopyFromRecordset rs 
     ' Close the recordset 
     rs.Close 
    Else 
     MsgBox "Error: No records returned.", vbCritical 
    End If 

    ' Clean up 
    If CBool(conn.State And adStateOpen) Then conn.Close 
    Set conn = Nothing 
    Set rs = Nothing 

End Sub 

私は接続を開こうとすると、以下を得続ける:これは私が現在持っているものです。接続文字列で何が問題になっていますか?

External table is not in the expected format

私はFollowingを発見し、ことを私のコードを変更:

sConnString = "provider=Microsoft.Jet.OLEDB.12.0;data source=" & _ 
        "C:\Users\dblois\Desktop\Shareenas Report.xlsx" + ";Extended Properties=Excel 12.0;" 

その後、私は次のエラーを取得しています:

Provider cannot be found. It may not be property installed

+0

@Comintern、no。元の質問をさらにいくつかの情報で更新しました。 – djblois

+0

代わりに[ACEドライバ](https://www.connectionstrings.com/ace-oledb-12-0/xlsx-files/)を代わりに使用します。 – Comintern

+0

@Cominternあなたはドライバが何と呼ばれているか知っていますか? – djblois

答えて

2

最初の試みで、あなたのOLEDBドライバは適していませんExcelファイルタイプ。 2番目の試みでは、Jetの12.0バージョンがないため、間違ったOLEDBドライバがあります。投稿したリンクの@Cominternのコメントと回答は、ACEドライバのバージョンを使用してください。しかし、両方のタイプに注意してください。ドライバの32/64ビットバージョンは、MS Officeのビットバージョン、またはExcelデータソースに接続しようとするその他のプログラム(PHP、Python、Javaなど)と一致する必要があります。

古いExcelの.xlsファイルの場合は、そのファイルの種類を認識しませんので、このエンジンがまだの.xlsx形式の知らないとしてJetを使用してます:より最近のExcelファイルの場合

strConnection = "Provider=Microsoft.JET.OLEDB.4.0;" _ 
        & "Data Source='C:\Path\To\Excel.xls';" _ 
        & "Extended Properties=""Excel 8.0;HDR=YES;"";" 

(。あるいは、

strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" _ 
        & "Data Source='C:\Path\To\Excel.xlsx';" _ 
        & "Extended Properties=""Excel 12.0 Xml;HDR=YES;"";" 

人によって使用される産業アプリケーション接続層であるODBCを使用:XLSX、.xlsm、.xlsb)、あなたはまた、.XLSタイプのための後方互換性のあるACEを使用しますy外部のバックエンドソースに接続するためのWindows以外のシステムでさえプログラムします。オープンソースのプログラミング言語でさえ、PHPのPDO、Pythonのpyodbc、R's RODBCなどのODBC APIを維持しています。古いソースフォーマットについて

:新しいソースフォーマットについて

strConnection = "DRIVER={Microsoft Excel Driver (*.xls)};" _ 
        & "DBQ=C:\Path\To\Excel.xlsx;" 

strConnection = "DRIVER={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};" _ 
        & "DBQ=C:\Path\To\Excel.xlsx;" 

とドライバビットverisonsの同じ原理はの.accdbバージョンVS MSアクセス.MDBに適用されます。

-2

あなたは何について話していますか? 「別のExcelブックからデータを取得するために、Excelでクエリを実行するための接続文字列とSQLスクリプトを作成する」とは何ですか?

1つのExcelファイルから別のExcelファイルにデータをコピーする場合は、これを試してください。

Sub VBA_Read_External_Workbook() 

    '''''Define Object for Target Workbook 
    Dim Target_Workbook As Workbook 
    Dim Source_Workbook As Workbook 
    Dim Target_Path As String 

    '''''Assign the Workbook File Name along with its Path 
    '''''Change path of the Target File name 
    Target_Path = "D:\Sample.xlsx" 
    Set Target_Workbook = Workbooks.Open(Target_Path) 
    Set Source_Workbook = ThisWorkbook 

    '''''With Target_Workbook object now, it is possible to pull any data from it 
    '''''Read Data from Target File 
    Target_Data = Target_Workbook.Sheets(1).Cells(1, 1) 
    Source_Workbook.Sheets(1).Cells(1, 1) = Target_Data 

    '''''Update Target File 
    Source_data = Source_Workbook.Sheets(1).Cells(3, 1) 
    Target_Workbook.Sheets(1).Cells(2, 1) = Source_data 

    '''''Close Target Workbook 
    Source_Workbook.Save 
    Target_Workbook.Save 
    Target_Workbook.Close False 

    '''''Process Completed 
    MsgBox "Task Completed" 

End Sub 

またはMAYBE。 。 。

Sub Write_To_Open_Excel() 
    Dim wb As Workbook 

    'Reference Workbook with its name 
    Workbooks("Book2").Worksheets("Sheet2").Activate 
    Workbooks("Book3.xls").Worksheets("Sheet2").Activate 

    'Search for Each Opened Workbook 
    For Each wb In Workbooks 
     If wb.Name = "Book2" Then 
      wb.Sheets(1).Cells(1, 1) = "Writing To Open Excel Worksheet - Testing" 
     End If 
    Next 
End Sub 

ここで、SQL ServerからExcelにデータを取り込む場合は、これを試してみてください。

Sub ADOExcelSQLServer() 
    ' Carl SQL Server Connection 
    ' 
    ' FOR THIS CODE TO WORK 
    ' In VBE you need to go Tools References and check Microsoft Active X Data Objects 2.x library 
    ' 

    Dim Cn As ADODB.Connection 
    Dim Server_Name As String 
    Dim Database_Name As String 
    Dim User_ID As String 
    Dim Password As String 
    Dim SQLStr As String 
    Dim rs As ADODB.Recordset 
    Set rs = New ADODB.Recordset 

    Server_Name = "EXCEL-PC\EXCELDEVELOPER" ' Enter your server name here 
    Database_Name = "AdventureWorksLT2012" ' Enter your database name here 
    User_ID = "" ' enter your user ID here 
    Password = "" ' Enter your password here 
    SQLStr = "SELECT * FROM [SalesLT].[Customer]" ' Enter your SQL here 

    Set Cn = New ADODB.Connection 
    Cn.Open "Driver={SQL Server};Server=" & Server_Name & ";Database=" & Database_Name & _ 
    ";Uid=" & User_ID & ";Pwd=" & Password & ";" 

    rs.Open SQLStr, Cn, adOpenStatic 
    ' Dump to spreadsheet 
    With Worksheets("sheet1").Range("a1:z500") ' Enter your sheet name and range here 
     .ClearContents 
     .CopyFromRecordset rs 
    End With 
    '   Tidy up 
    rs.Close 
    Set rs = Nothing 
    Cn.Close 
    Set Cn = Nothing 
End Sub 

最後に、ExcelからSQL Serverにデータを送信する場合は、これを試してください。

Sub ButtonClick() 
'TRUSTED CONNECTION 
    On Error GoTo errH 

    Dim con As New ADODB.Connection 
    Dim rs As New ADODB.Recordset 
    Dim strPath As String 
    Dim intImportRow As Integer 
    Dim strFirstName, strLastName As String 

    Dim server, username, password, table, database As String 


    With Sheets("Sheet1") 

      server = .TextBox1.Text 
      table = .TextBox4.Text 
      database = .TextBox5.Text 


      If con.State <> 1 Then 

       con.Open "Provider=SQLOLEDB;Data Source=" & server & ";Initial Catalog=" & database & ";Integrated Security=SSPI;" 
       'con.Open 

      End If 
      'this is the TRUSTED connection string 

      Set rs.ActiveConnection = con 

      'delete all records first if checkbox checked 
      If .CheckBox1 Then 
       con.Execute "delete from tbl_demo" 
      End If 

      'set first row with records to import 
      'you could also just loop thru a range if you want. 
      intImportRow = 10 

      Do Until .Cells(intImportRow, 1) = "" 
       strFirstName = .Cells(intImportRow, 1) 
       strLastName = .Cells(intImportRow, 2) 

       'insert row into database 
       con.Execute "insert into tbl_demo (firstname, lastname) values ('" & strFirstName & "', '" & strLastName & "')" 

       intImportRow = intImportRow + 1 
      Loop 

      MsgBox "Done importing", vbInformation 

      con.Close 
      Set con = Nothing 

    End With 

Exit Sub 

errH: 
    MsgBox Err.Description 
End Sub 

またはMAYBE。 。 。

Sub InsertInto() 

'Declare some variables 
Dim cnn As adodb.Connection 
Dim cmd As adodb.Command 
Dim strSQL As String 

'Create a new Connection object 
Set cnn = New adodb.Connection 

'Set the connection string 
cnn.ConnectionString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=Northwind;Data Source=Excel-PC\SQLEXPRESS" 
'cnn.ConnectionString = "DRIVER=SQL Server;SERVER=Excel-PC\SQLEXPRESS;DATABASE=Northwind;Trusted_Connection=Yes" 


'Create a new Command object 
Set cmd = New adodb.Command 

'Open the Connection to the database 
cnn.Open 

'Associate the command with the connection 
cmd.ActiveConnection = cnn 

'Tell the Command we are giving it a bit of SQL to run, not a stored procedure 
cmd.CommandType = adCmdText 

'Create the SQL 
strSQL = "UPDATE TBL SET JOIN_DT = '2013-01-22' WHERE EMPID = 2" 

'Pass the SQL to the Command object 
cmd.CommandText = strSQL 


'Execute the bit of SQL to update the database 
cmd.Execute 

'Close the connection again 
cnn.Close 

'Remove the objects 
Set cmd = Nothing 
Set cnn = Nothing 

End Sub 
関連する問題