Office 2013

时间:2018-03-23 10:57:11

标签: excel vba excel-vba

我有一个代码应该更新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

我无法理解为什么代码在办公室2013不起作用。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

尝试以下两种方法之一:

  1. 在两个版本的Debug.Print a之前写.CommandText并确保结果相同

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

  3. (3。)@Peh的评论是一个重点。您需要显式声明每个变量类型。例如。 Dim a as Long, x as Variant, year as Long, month as Long, day as String

答案 1 :(得分:0)

问题显然是由使用相同连接的多个枢轴引起的。更多详情:https://www.experts-exchange.com/questions/25840229/How-do-I-programmatically-changing-the-Command-Text-property-of-a-Connection-in-MS-Excel-2007.html

在更新命令文本然后将其更改回来之前,将连接类型从ODBC更改为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