Vba office 2013中的CommandText非运行时错误1004

Vba office 2013中的CommandText非运行时错误1004,vba,excel,Vba,Excel,我有一个代码,可以更新excel中连接的sql查询中的日期。日期决定了数据将来自哪个表。该代码在windows 10上的office 2016中正常工作。但是,我得到运行时错误 1004:“应用程序定义或对象定义错误” 当我在windows 8上的office 2013中运行同一宏时,在.CommandText行上 有什么办法解决这个问题吗 Sub change_date() Dim a As String, x As String, year As String, month As Stri

我有一个代码,可以更新excel中连接的sql查询中的日期。日期决定了数据将来自哪个表。该代码在windows 10上的office 2016中正常工作。但是,我得到运行时错误

1004:“应用程序定义或对象定义错误”

当我在windows 8上的office 2013中运行同一宏时,在.CommandText行上

有什么办法解决这个问题吗

Sub change_date()

Dim a As String, x As String, year As String, month As String, day As String, datebox As Variant

'Get the day, month and year from name of the workbook
x = ActiveWorkbook.Name
year = Mid(x, 1, 4)
month = Mid(x, 5, 2)
day = Mid(x, 7, 2)

'Ask user if he/she wants to change the date
    datebox = InputBox("Is the report date " & _
    day & "." & month & "." & year & _
    "?" & vbNewLine & vbNewLine & _
    "If not, please enter the report date below as YYYY-MM-DD and click 'OK'." & vbNewLine & vbNewLine & _
    "If that is the correct date, click 'OK' or 'Cancel' without entering anything below")
If datebox = "" Then
    x = year & "-" & month & "-" & day
Else
    x = datebox
End If

'Update the query with the report date
With ActiveWorkbook.Connections("postgres y_original_customer_info").ODBCConnection
a = "SELECT * FROM public.f_customers_with_pllm_and_gkh('"
a = a & x
a = a & "')"

'Following line gives Runtime error 1004
.CommandText = a

'Following also gives error
'.CommandText = Array("SELECT * FROM public.f_exposures_with_sllp_and_cqs('" & x & "')")

.Refresh
End With
End Sub
我不明白为什么该代码在office 2013中不起作用。任何帮助都将不胜感激

尝试以下两种方法之一:

  • 在两个版本中,在
    .CommandText
    之前写入
    Debug.Print a
    ,并确保结果相同

  • 检查两个文件中的
    ODBCConnection
    。例如,在两个地方重建


  • (3)"Peh"的评论很重要。您需要显式声明每个变量类型。例如,
    Dim a as Long,x as Variant,year as Long,month as Long,day as String
    问题显然是由使用同一连接的多个枢轴引起的。更多详情:

    在更新命令文本之前将连接类型从ODBC更改为OLEDB,然后将其更改回OLEDB有助于解决此问题

    我添加了以下代码:

    With ActiveWorkbook.PivotCaches(1)
    If .QueryType = xlODBCQuery Then
        strConnection = Replace(.Connection, "ODBC;DSN", "OLEDB;DSN", 1, 1, vbTextCompare)
        .Connection = strConnection
        'Update the sql query
        .CommandText = strSQL
    
    'Change connection back to ODBC
        strConnection = Replace(.Connection, "OLEDB;DSN", "ODBC;DSN", 1, 1, vbTextCompare)
        .Connection = strConnection
    
    'If connection is not ODBC, then update the query right away
    Else 
        .CommandText = strSQL
    
    End If
    

    只需注意:
    Dim a,x,年,月,日作为字符串
    只声明
    day作为字符串
    所有其他都是
    变量
    。您需要为每个变量指定一个类型。也许这对你有帮助。@Pᴇʜ谢谢你的警告,我确实按照你说的详细说明了一切。谢谢,但这对我的问题没有帮助。Print在两个版本中给出相同的结果。2.没有帮助解决此问题,在Office 2013中仍然出现相同的错误。