2017-05-02 161 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。