使用vbscript查询excel文件时,条件表达式中的数据类型不匹配

时间:2011-08-30 08:57:47

标签: excel vbscript

我有一个场景,我必须使用SQL查询excel表。 在excel中,我有一个名为“test_case_id”的列,它包含字母数字值 我使用以下vbscript代码从excel获取值。 excel中的“test_case_id”列已格式化为“常规”。 当此列的值是整数(例如:1,2,3 ...)

SELECT  *   FROM [05 Invest Allocate$] WHERE [test_case_id] =1

以上查询似乎有效

但是当“test_case_id”列中有一个字符时(例如:5b,6b,7b)

SELECT  *   FROM [05 Invest Allocate$] WHERE [test_case_id] ='5b'

上述查询给出错误“条件表达式中的数据类型不匹配。”

有人可以帮我解决这个问题,我可以在where子句中查询字符串或整数吗?

完整代码是:

strQuery = "SELECT  *   FROM [05 Invest Allocate$] WHERE [test_case_id] ='5b'"
j_drive_root_path="C:\Documents and Settings\Desktop\"

Set objNetwork = CreateObject("WScript.Network")
            strUserName =objNetwork.UserName

            Set fso = CreateObject("Scripting.FileSystemObject")
            Set original = fso.GetFile(j_drive_root_path & "temp_invest_allocate.xls")

            strCopyPath = "C:\Documents and Settings\" & strUsername & "\copyofexceltable.xls"
            original.Copy (strCopyPath)

            'Set the connection object and path to the copied spreadsheet       
            Set objAdCon =  CreateObject("ADODB.Connection")

            strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
                    "Data Source=" & strCopyPath & ";" & _
                      "Extended Properties=""Excel 8.0;HDR=Yes"""

            'Open spreadsheet
            objAdCon.Open strConn

            'Create a recordest object (to store the results of the query)
            Set record_set = CreateObject("ADODB.Recordset")

            'Run the query
            record_set.CursorLocation = 3

            record_set.Open strQuery, objAdCon, 1, 3

            If Not record_set.EOF Then
                Set client_to_accountID = CreateObject("Scripting.Dictionary")
                client_to_accountID.CompareMode=vbTextCompare
                client_to_accountID.RemoveAll

                Do Until record_set.EOF
                        tmp_val=Trim(Cstr(record_set("id").Value))
                        print "id=" & tmp_val
                        record_set.MoveNext
                Loop
            End If ' End of if not record_set.EOF

2 个答案:

答案 0 :(得分:1)

如果您使用的是Win7 64位,则该位置为“我的电脑”\ HKEY_LOCAL_MACHINE \ SOFTWARE \ Wow6432Node \ Microsoft \ Jet \ 4.0 \ Engines \ Excel

答案 1 :(得分:0)

http://support.microsoft.com/kb/257819中声明:

  

例如:在您的八(8)个扫描行中,如果列包含   五(5)个数值和三(3)个文本值,提供者   返回五(5)个数字和三(3)个空值。在你的八(8)   扫描行,如果列包含三(3)个数值和五个   (5)文本值,提供者返回三(3)个空值和五个   (5)文本值。在您的八(8)个扫描行中,如果是列   包含四(4)个数值和四(4)个文本值,   provider返回四(4)个数字和四(4)个空值。作为一个   结果,如果您的列包含混合值,您唯一的办法就是   将该列中的数值存储为文本,并将其转换回来   使用Visual在客户端应用程序中需要时编号   基本VAL函数或等效函数。

     

要解决此问题以获取只读数据,请启用“导入模式”   使用“扩展属性”部分中的“IMEX = 1”设置   连接字符串。这将强制执行ImportMixedTypes = Text注册表   设置。但请注意,更新可能会产生意外结果   这种模式。有关此设置的其他信息,请单击   下面的文章编号,以查看Microsoft知识中的文章   基数:194124 PRB:Excel值使用DAO返回为NULL   OpenRecordset

您可能需要在

的注册表中将TypeGuessRows更改为0
Hkey_Local_Machine/Software/Microsoft/Jet/4.0/Engines/Excel/