我正在尝试使用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端可能缺少参考库,还是日期格式问题?
您是为了该帖子的目的而添加了这些续行,还是代码与VBE编辑器中的相同?由于字符串文字不能像这样跨越多行......该代码无法编译。 –