excel vba sql server数据导入“类型不匹配错误”

时间:2012-03-28 13:19:46

标签: sql excel vba import

我正在尝试创建一个宏,将一些数据从SQL Server 2005中提取到Excel 2003中。

SQL代码位于此宏中,部分代码来自Excel中单元格中的值。这在某种程度上有效,但是当我用于SQL代码的Excel单元格中的数据超出公式预览中的一行(或大约170个字符)时,我得到“类型不匹配”错误。否则它可以正常工作。

With ActiveSheet.QueryTables.Add(Connection:=Array( _
"OLEDB;Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;Data       Source=anglobisql;Use Procedure for Prepare=1;Auto " _
    , _
    "Translate=True;Packet Size=4096;Workstation ID=MyIDHere;Use Encryption for Data=False;Tag with column collation when possible=F" _
    , "alse;Initial Catalog=DATABASENAME"), Destination:=Range("A1"))
    .CommandType = xlCmdSql
    .CommandText = Array("SELECT COLUMN1, COLUMN2 FROM TABLENAME (nolock) WHERE COLUMN1 IN (" & ActiveWorkbook.Sheets("Sheet1").Range("e607").Value & ")")
    .Name = "DATABASE TABLENAME"
    .FieldNames = True
    .RowNumbers = False
    .FillAdjacentFormulas = False
    .PreserveFormatting = True
    .RefreshOnFileOpen = False
    .BackgroundQuery = True
    .RefreshStyle = xlInsertDeleteCells
    .SavePassword = False
    .SaveData = True
    .AdjustColumnWidth = True
    .RefreshPeriod = 0
    .PreserveColumnInfo = True
    .SourceConnectionFile = _
    "H:\My Data Sources\DATABASE TABLENAME.odc"
    .Refresh BackgroundQuery:=False

显然,所有databasename和tablename都已正确填写。

知道这是为什么会掉下来(是否存在字符限制,或者是否因为单元格值继续到Excel中的公式预览栏中的下一行而失败?如何修复?

非常感谢,

亚历

2 个答案:

答案 0 :(得分:0)

Excel单元格超过170个字符不应导致任何问题。我建议将出错的行分开,以帮助找到问题的确切位置。

替换它:

    .CommandText = Array("SELECT COLUMN1, COLUMN2 FROM TABLENAME (nolock) WHERE COLUMN1 IN (" & ActiveWorkbook.Sheets("Sheet1").Range("e607").Value & ")")

有了这个:

    Dim rng As Range, sSql As String
    Set rng = ActiveWorkbook.Sheets("Sheet1").Range("e607")
    Debug.Print "Range.Value = |" & rng.Value & "|"
    sSql = "SELECT COLUMN1, COLUMN2 FROM TABLENAME (nolock) WHERE COLUMN1 IN (" & rng.Value & ")"
    Debug.Print "SQL = |" & sSql & "|"
    .CommandText = sSql

Debug.Print将打印到即时窗口,以便您可以仔细检查变量是否符合您的预期。在调试字符串时,我喜欢使用|而不是"因为我几乎从不在字符串中使用|

另外,我不会因为Array()CommandText使用Connection而烦恼。为了便于阅读,我会重做你的第一行看起来像这样。

With ActiveSheet.QueryTables.Add( _
        Connection:="OLEDB;Provider=SQLOLEDB.1;Integrated Security=SSPI" _
                & ";Persist Security Info=True;Data Source=anglobisql" _
                & ";Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096" _
                & ";Workstation ID=MyIDHere;Use Encryption for Data=False" _
                & ";Tag with column collation when possible=False;Initial Catalog=DATABASENAME" _
      , Destination:=Range("A1"))

答案 1 :(得分:0)

通过删除数组文本来解决这个问题

.CommandText = Array("SELECT COLUMN1, COLUMN2 FROM TABLENAME (nolock) WHERE ...

变为

.CommandText = ("SELECT COLUMN1, COLUMN2 FROM TABLENAME (nolock) WHERE ...