2017-05-02 164 views
0

我正在嘗試使用Excel VBA和SQL Server檢索DISTINCT值。我建立了與數據庫的連接並可以運行其他查詢;但是,下面的SQL查詢導致我的VBA代碼打破:使用Excel VBA問題查詢SQL Server

SQL語句:

Select DISTINCT ZoneName, IsoName From vDeal 
Where PeriodMonth >= '2015-03-01' 
Order by IsoName, ZoneName ASC 

Excel的VBA:

With ActiveSheet.ListObjects.Add(SourceType:=0, Source:= _ 
    "OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$; & _ 
    Location=LOADZONE_DISTINCT", Destination:=Range("$C$1")).QueryTable 
    .CommandText = "Select DISTINCT ZoneName, IsoName From vDeal Where PeriodMonth >= & _ 
     '2015-03-01' Order by IsoName, ZoneName ASC" 
    .CommandType = xlCmdSql 
    .RowNumbers = False 
    .FillAdjacentFormulas = False 
    .PreserveFormatting = True 
    .RefreshOnFileOpen = False 
    .BackgroundQuery = True 
    .RefreshStyle = xlInsertDeleteCells 
    .SavePassword = False 
    .SaveData = True 
    .AdjustColumnWidth = True 
    .RefreshPeriod = 0 
    .PreserveColumnInfo = True 
    .ListObject.DisplayName = "LOADZONE_DISTINCT" 
    .Refresh BackgroundQuery:=False 
End With 

The field PeriodMonth is a date formatted "yyyy-mm-dd"

Excel error: "Run-time error '1004': Application-defined or object defined error

SQL查詢完全在MS SQL即成管理工作室,所以在Excel方面必須有細分。在VBA端可能缺少參考庫,還是日期格式問題?

+0

您是爲了該帖子的目的而添加了這些續行,還是代碼與VBE編輯器中的相同?由於字符串文字不能像這樣跨越多行......該代碼無法編譯。 –

回答

0

工作了使用ActiveX數據對象以不同的方式。

Dim strSql As String 
Dim rs As ADODB.Recordset 
Dim conn As ADODB.Connection 

Dim wks As Worksheet 
Set wks = ThisWorkbook.Worksheets("Sheet1") 

Set rs = New ADODB.Recordset 
Set conn = New ADODB.Connection 

conn.ConnectionString = "Provider=####;Data Source=####;Initial Catalog=####;User ID=####;Password=####" 
conn.ConnectionTimeout = 300 
conn.CursorLocation = adUseClient 
conn.Open 

strSql1 = "Select DISTINCT ZoneName, IsoName From vDeal Where ZoneName Is NOT NULL and IsoName IS NOT NULL and PeriodMonth > '2015-03-01' Order by IsoName, ZoneName ASC" 

rs.Open strSql1, conn 
If rs.RecordCount = 0 Then 
    wks.Range(Cells(1, 1).Address).Value = "No Data" 
Else 
    wks.Range(Cells(1, 1).Address).CopyFromRecordset rs 
    For i = 0 To rs.Fields.Count - 1 
     wks.Range(Cells(1, 1).Address).Range("A1").Offset(0, i) = rs.Fields.Item(i).Name 
    Next i 
End If 

rs.Close 

在VBA參考中使用Microsoft ActiveX Data Objects 2.8 Library。