在Excel

时间:2016-05-26 16:19:51

标签: sql excel vba excel-vba

以下查询在excel中提供结果:“Expr1000 RESULT”我需要得到没有标题的结果,而我发现的任何内容都无法实现。我在查询中找不到任何冗余,但是当我删除SUM函数时,标头会恢复为列的正确标头。我非常感谢任何想法。

  
Sub CalculateComplete()
Sheet2.Cells.ClearContents

Dim oCn As ADODB.Connection
Dim oRS As ADODB.Recordset
Dim ConnString As String
Dim SQL As String

Dim QueryDPiN As String
QueryDPiN = "SELECT IIF(SUM([Amount Due]) IS NULL, 0, SUM([Amount Due])) FROM [OP$] WHERE [Originator Dept]='BLC New Business' AND [Overpayment Category]='Dollars Paid in Error';"

Call SQLQueries(QueryDPiN, "C2")

End Sub

Sub SQLQueries(QueryVariable As String, TableLocation As String)

Dim oCn As ADODB.Connection
Dim oRS As ADODB.Recordset
Dim ConnString As String
Dim SQL As String
Dim qt As QueryTable

ConnString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\cnop0g\Desktop\OP.xlsx;Extended Properties=Excel 8.0;Persist Security Info=False"
Set oCn = New ADODB.Connection
oCn.ConnectionString = ConnString
oCn.ConnectionTimeout = 30
oCn.Open

SQL = QueryVariable

Set oRS = New ADODB.Recordset
oRS.Source = SQL
oRS.ActiveConnection = oCn
oRS.Open

Set qt = Worksheets(6).QueryTables.Add(Connection:=oRS, _
Destination:=Worksheets(6).Range(TableLocation))

    qt.Refresh

If oRS.State <> adStateClosed Then
oRS.Close
End If

If Not oRS Is Nothing Then Set oRS = Nothing
If Not oCn Is Nothing Then Set oCn = Nothing

End Sub

感谢您的帮助!   - Zokah

1 个答案:

答案 0 :(得分:1)

您需要在查询中指定列名AS [Amount Due],以便SQL引擎不会自动生成一个:

QueryDPiN = "SELECT IIF(SUM([Amount Due]) IS NULL, 0, SUM([Amount Due])) AS [Amount Due] FROM [OP$] WHERE [Originator Dept]='BLC New Business' AND [Overpayment Category]='Dollars Paid in Error';"