【问题标题】:Querying SQL Server using Excel VBA issues使用 Excel VBA 问题查询 SQL Server
【发布时间】:2017-05-10 01:50:59
【问题描述】:

我正在尝试使用 Excel VBA 和 SQL Server 检索 DISTINCT 值。我已经建立了与数据库的连接并且可以运行其他查询;但是,以下 SQL 查询导致我的 VBA 代码中断:

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

字段 PeriodMonth 是格式为“yyyy-mm-dd”的日期

Excel 错误:“运行时错误‘1004’:应用程序定义或对象定义错误

SQL 查询在 MS SQL Serve Management Studio 中完美运行,因此 Excel 端肯定有故障。 VBA 端是否缺少参考库,还是日期格式问题?

【问题讨论】:

  • 您添加这些续行是为了发帖,还是代码与 VBE 编辑器中的代码相同?因为字符串文字不能像这样跨越多行......该代码无法编译。

标签: sql-server excel vba


【解决方案1】:

如果代码与 VBE 编辑器中的代码相同,请更改此行

.CommandText = " Select DISTINCT ZoneName, IsoName From vDeal Where PeriodMonth >= " & _
    " '2015-03-01' Order by IsoName, ZoneName ASC "

供参考https://msdn.microsoft.com/en-us/library/dd627355(v=office.12).aspx#Access2007BuildingSQLStatements_UsingStringCriteria

【讨论】:

  • 抱歉,这是为了网站的可读性。我会进行编辑。
【解决方案2】:

使用 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 数据对象 2.8 库。

【讨论】:

    猜你喜欢
    • 2013-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-07
    • 1970-01-01
    相关资源
    最近更新 更多