我正在嘗試使用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編輯器中的相同?由於字符串文字不能像這樣跨越多行......該代碼無法編譯。 –