将结果从数据库中拉入Excel

时间:2015-09-15 20:17:01

标签: excel vba excel-vba

我无法使用此代码。我第一次运行它时,它提示我输入密码,宏每次都完成,但不会将结果拉到sheet1。我能在这做什么?

Sub Update()

    ThisWorkbook.Sheets("sheet1").Activate
    ThisWorkbook.Sheets("sheet1").Range("A1").Select
    Dim strStDt As String
    Dim strEnDt As String
    Dim strSQL As String

    strStDt = ThisWorkbook.Worksheets("lookup").Range("B6").Value
    strEnDt = ThisWorkbook.Worksheets("lookup").Range("B5").Value

    strSQL = ""
    strSQL = strSQL & "SELECT tkt.cntry_istto"
    strSQL = strSQL & ",tkt.pod"

    strSQL = strSQL & " FROM INTGY.GRUIP tkt"

    strSQL = strSQL & " Where tky.year_month_nbr between " & strStDt & " and " & strEnDt


    ThisWorkbook.Sheets("sheet1").Activate
    ThisWorkbook.Sheets("sheet1").Range("A1").Select

    With ActiveWorkbook.Connections(1).ODBCConnection

        .BackgroundQuery = True
        .Connection = "ODBC;DSN=#EDXX;UID=;;DATABASE=INTGY; AUTHENTICATION=;"
        .CommandText = strSQL
        .RefreshOnFileOpen = False
        .SavePassword = False
        .SourceConnectionFile = ""
        .SourceDataFile = ""
        .ServerCredentialsMethod = xlCredentialsMethodIntegrated
        .AlwaysUseConnectionFile = False
        .Refresh

    End With

End Sub

2 个答案:

答案 0 :(得分:0)

您是否确认在查询中正确输入了strSQL?将Msgbox strSQL放在With ActiveWorkbook.Connections(1).ODBCConnection之前,并确保其按预期显示。

此外,所有这些:

strSQL = ""
strSQL = strSQL & "SELECT tkt.cntry_istto"
strSQL = strSQL & ",tkt.pod"

strSQL = strSQL & " FROM INTGY.GRUIP tkt"

strSQL = strSQL & " Where tky.year_month_nbr between " & strStDt & " and " & strEnDt

可以改写为:

strSQL = "SELECT tkt.cntry_istto,tkt.pod FROM INTGY.GRUIP tkt Where tky.year_month_nbr between " & strStDt & " and " & strEnDt

答案 1 :(得分:0)

使用ADO connection检索记录集,然后使用CopyFromRecordset复制到工作表范围(仅指定左上角的单元格)。

另外,我不知道数据库,但要注意你的日期必须用单引号括起来(对于大多数数据库),或者如果使用MS Access封装#而不是引号。

Dim conn As Object 
Dim rst As Object
Dim strSQL As String, strStDt As String, strEnDt As String

Set conn = CreateObject("ADODB.Connection") 
Set rst = CreateObject("ADODB.Recordset")

strStDt = ThisWorkbook.Worksheets("lookup").Range("B6")
strEnDt = ThisWorkbook.Worksheets("lookup").Range("B5")

strSQL = "SELECT tkt.cntry_istto, tkt.pod"
strSQL = strSQL & " FROM INTGY.GRUIP tkt"
strSQL = strSQL & " WHERE tkt.year_month_nbr"
strSQL = strSQL & " BETWEEN '" & strStDt & "' and '" & strEnDt & "'

conn.Open "DSN=#EDXX"
rst.Open strSQL, conn

ThisWorkbook.Sheets(1).Range("A1").CopyFromRecordest rst
rst.Close

Set rst = Nothing 
Set conn = Nothing