2017-09-05 26 views
0

您好:我已经成功将一个长SQL(Oracle)作为手动输入的OLEDB数据连接中的命令文本。然后我通过VBA成功进入SQL(因为我需要它根据不断变化的Item List进行更新),并且只运行联合查询的第一部分作为测试。Excel VBA:OLEDB Connection.CommandText错误

但是,当我做了最后一项更改时,向联合查询添加了第二块,并且使strQuery命令包含三个单独的查询字符串,现在它在此行代码中引发错误:.CommandText = StrQueryAll

StrQueryAll = StrQueryBegin & StrQueryAZ & StrQueryCO & StrQueryEnd 

    With ActiveWorkbook.Connections("connection_name").OLEDBConnection 
     .CommandText = StrQueryAll 
     .Refresh 
    End With 

以下是删除了实际sql的完整代码。 sql的代码是否有问题太久?或者也许是另一个问题,但它间接地说有错误?也许它不喜欢strQueryAll命令?我可以做一个大的sql字符串,并在延续限制的基础上添加字符串,但认为它可能更清晰地分解sqls。

感谢您的帮助!

Private Sub Refresh_Data() 

Dim cnn As New ADODB.Connection 
Dim rst As New ADODB.Recordset 
Dim ConnectionString As String 
Dim StrQueryAll As String 
Dim StrQueryBegin As String 
Dim StrQueryAZ As String 
Dim StrQueryCO As String 
Dim StrQueryCA As String 
Dim StrQueryEnd As String 
Dim Item_List As String 
Dim wksItemList As Worksheet 
Dim wksDataTable As Worksheet 
Dim rngItems As Range 
Dim rngDatatbl As Range 

Dim myMSG As String 
'Dim pt As PivotTable 

myString = "Refreshing Tables - Please Wait" 
Application.StatusBar = myString 

'With Application 
    '.EnableEvents = False 
    '.ScreenUpdating = False 
'End With 

    Set wksItemList = Worksheets("Items") 
    Set rngItems = wksItemList.Range("E4") 
    Set wksDataTable = Worksheets("data") 
    Set rngDatatbl = wksDataTable.Range("A3") 

Item_List = rngItems.Value 

StrQueryBegin = "SELECT " & Chr(13) & "" & Chr(10) & _ 
    ..... more sql.... 

    .... next sql string .... 
      StrQueryAZ = " -- **** AZ ****" & Chr(13) & "" & Chr(10) & _ 
      " select" & Chr(13) & "" & Chr(10) & _ 
    ..... more sql.... 

    .... next sql string .... 
StrQueryCO = Chr(13) & "" & Chr(10) & " UNION " & Chr(13) & "" & Chr(10) & _ 
      " -- **** CO SYS ****" & Chr(13) & "" & Chr(10) & _ 
      " select " & Chr(13) & "" & Chr(10) & _ 
    ..... more sql.... 

    .... next sql string .... 
StrQueryEnd = "   ) " & Chr(13) & "" & Chr(10) & _ 
      " ORDER BY " & Chr(13) & "" & Chr(10) & _ 
      " ITEM_NBR, WHS " & Chr(13) & "" & Chr(10) 

Debug.Print StrQueryBegin & StrQueryAZ & StrQueryCO & StrQueryEnd 
StrQueryAll = StrQueryBegin & StrQueryAZ & StrQueryCO & StrQueryEnd 


    With ActiveWorkbook.Connections("connection_name").OLEDBConnection 
     .CommandText = StrQueryAll 
     .Refresh 
    End With 
+0

什么是错误?没有看到SQL代码就可能发现问题。 – user1274820

+0

对不起,我没有忘记补充说...它是运行时错误1004:应用程序定义或对象定义的错误。我知道这并没有帮助。我已经发布了整个代码没有查询的详细信息。该查询起作用,并且我已经在vba中对此进行了测试。我会继续测试,看看我能否回溯。 – RARascon

+0

我也忘了补充说的是我之前没有得到那个错误,直到我加入到sql中。 – RARascon

回答

0

经过多次搜索和测试后,问题是总的CommandText字符已经超过了允许的32,767个字符。

user1274820:从某种意义上说,您是对的,您需要查看整个代码。 SQL很长,因为我们的表设置方式和sql长度是一个必要的罪恶。我会研究其他选项来运行这个。

+0

只是想说 - 你可能会考虑运行一些查询,使用VBA在Excel中组合数据,然后运行其他查询。我知道我遇到了一些问题,我的SQL变得非常复杂 - 我最终只是使用SQL来处理数据,并使用VBA处理它。 – user1274820