2014-08-27 4 views
0

작은 프로젝트에서 조금 머물렀다 여러 SQL 쿼리에서 결과를 생성하려면 SQL Server 2008을 사용하려고하는데 처음으로 코드를 작성합니다. VBA 나는 (A SQL 단일 쿼리에 대한)이 코드를 시도하지만, 난 여전히 컴파일 문제 excel에서 SQL 쿼리 실행

Sub New_Feuil1() 
    ThisWorkbook.Activate 

    'First clear the contents from the query 
    Worksheets("Feuil1").Select 
    Range("A2").Select 
    Do Until ActiveCell = "" 
     ActiveCell.Offset(1).Select 
    Loop 
    Range("A4", ActiveCell.Offset(-1, 3)).ClearContents 

    'Get reporting date 
    ReportingDate = ThisWorkbook.Sheets("Parameters").Range("D1") 

    'Format the value for use in the SQL query 
    ReportingDateFor = Format(ReportingDate, "yyyy-mm-dd") 

    Worksheets("Feuil1").Select 
    Range("A1").Select 

    Dim cnn As New ADODB.Connection 
    Dim rst As New ADODB.Recordset 
    Dim StrQuery1 As String 
    Dim ConnectionString As String 

    ConnectionString ="ODBC;" & _ 
    "Driver={SQL Server Native Client 10.0};" & _ 
    "Server=187.125.254.231;" & _ 
    "Database=database;" & _ 
    "UID=sa; PWD=pwd" 
    cnn.Open ConnectionString 
    cnn.CommandTimeout = 900 

    'Queries to be executed 
    StrQuery1 = StrQuery1 & "Select Id from Users" 

    rst.Open StrQuery1, cnn, adOpenForwardOnly, adLockReadOnly 
    rst.Close 

    Debug.Print "StrQuery1:"; StrQuery1 
    cnn.Close 

    ThisWorkbook.Sheets("Central Dashboard").Select 
    Sheets("Feuil1").Range("A2").CopyFromRecordset rst 

End Sub 

다른 솔루션이

있나요?

+1

당신이 ** 특정 ** 문제 (들) 당신이 겪고있는 우리에게 보여 주시겠습니까. [짧은, 자체 포함, 올바른 예를 작성하는 방법] (http://sscce.org/)을 읽고 여기 [도움말 센터] (http://stackoverflow.com/help)를보십시오. 그런 다음 질문을하고 필요한 모든 세부 사항을 제공하십시오 (http://stackoverflow.com/posts/25524210/edit). – RossC

+0

매번 매크로를 실행할 때마다 컴파일 문제가 있다고 계속 말합니다. – user3708197

+1

ok ... 컴파일 문제는 무엇입니까? 컴퓨터가 보이지 않습니다. 제가 제공 한 링크를 읽고 질문 내용을 편집하여 우리에게 무슨 일이 일어나는지 설명하십시오. "컴파일러 오류가 발생합니다." – RossC

답변

1

프로그래밍에 익숙하지 않은 것 같습니다. 어떤 변수를 사용하기 전에이를 선언하면 빨리 이해할 수 있습니다.

좋아 :

Dim ReportingDate as Date 
ReportingDate = ThisWorkbook.Sheets("Parameters").Range("D1") 

Dim ReportingDateFor As String 
ReportingDateFor = Format$(ReportingDate, "yyyy-mm-dd") 

은 또한 당신의 연결 문자열을 확인합니다. 이 연결 문자열을 시도하십시오.

ConnectionString = "Driver={SQL Server Native Client 10.0};Server=187.125.254.231;Database=database;UID=sa; PWD=pwd" 

그 외에도에서, 당신은 레코드 집합을 열고 레코드를 폐쇄하고 마지막으로 연결을 종료 한 다음 결과를 검색하려는 서버에 연결하는 코드를 찾고 있습니다. 논리적으로이 :) 작동하지 않을 것입니다 :)

이 시도 :

Dim cnn As New ADODB.Connection 
Dim rst As New ADODB.Recordset 
Dim cmd As ADODB.Command 

Dim ConnectionString As String 
ConnectionString = "Driver={SQL Server Native Client 10.0};Server=187.125.254.231;Database=database;UID=sa; PWD=pwd" 

cnn.Open ConnectionString 

'Queries to be executed 
Dim StrQuery1 As String 
StrQuery1 = StrQuery1 & "Select Id from Users" 

'Prepare SQL execution 
cmd.Name = "SelectUsers" 
cmd.ActiveConnection = conn 
cmd.CommandText = StrQuery1 

Set rst = cmd.Execute 
If Not rst.EOF Then 
    With Sheets(1).Cells ' Enter your sheet name and range here 
     .ClearContents ' clears the entire sheet 
     .CopyFromRecordset rst ' copy the result 
    End With 
Else 
    MsgBox "no records found.." 
End If 

'After work done close connection 
On Error Resume Next 
rst.Close 
cnn.Close 
Set rst = Nothing 
Set cnn = Nothing