vba 运行时错误 '-2147352571(80020005) 类型不匹配
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22878697/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Run-time error '-2147352571(80020005) Type mismatch
提问by user3391281
I have Run-time error '-2147352571(80020005) Type mismatch
in line .AddItem rs(1)
:
我有Run-time error '-2147352571(80020005) Type mismatch
在行.AddItem rs(1)
:
Private Sub UserForm_Activate()
If dbconn.State = adStateClosed Then dbconn.Open strConn
Dim rs As New ADODB.Recordset
ListBox1.Clear
ListBox1.ColumnCount = 6
rs.Open "select idClient,client_name,Address,City,state,country from tblClients ", dbconn
Do While rs.EOF = False
i = i + 1
With UserForm2.ListBox1
.AddItem rs(1) '---------> getting ERROR HERE PLEASE LET ME KNOW
.List(.ListCount - 1, 1) = rs(2)
.List(.ListCount - 1, 2) = rs(3)
.List(.ListCount - 1, 3) = rs(4)
.List(.ListCount - 1, 4) = rs(5)
.List(.ListCount - 1, 5) = rs(0)
End With
rs.MoveNext
Loop
rs.Close
With cmbCountry
.AddItem "United States"
.AddItem "Canada"
.AddItem "Germany"
.AddItem "Australia"
End With
cmbCountry.ListIndex = 0
End Sub
回答by z32a7ul
I think you should start the debugger when the error occurs. Then in the Immediate Window write ? rs(1)
. If this throws an error, then the rs(1) part is faulty, otherwise the problem is with the .AddItem
.
我认为您应该在发生错误时启动调试器。然后在立即窗口中写入? rs(1)
. 如果这引发错误,则 rs(1) 部分有问题,否则问题出在.AddItem
.
In the first case, watch rs in a Watch Window, and determine what properties it has. Maybe it does not have a default property by which you can access the first of something as you try with rs(1)
. I suppose you are interested in one of the fields, so I would try ? rs.Fields(1)
.
在第一种情况下,在 Watch Window 中观察 rs,并确定它具有哪些属性。也许它没有默认属性,您可以在尝试使用rs(1)
. 我想您对其中一个领域感兴趣,所以我会尝试?rs.Fields(1)
.
In the second case rs(1) returns something that is not convertible to string. You may try ? CStr(rs(1))
to see whether it can be converted or watch it in the Watch window. But how you continue from there depends on what you find.
在第二种情况下 rs(1) 返回一些不可转换为字符串的内容。您可以尝试? CStr(rs(1))
查看是否可以转换或在观看窗口中观看。但是你如何从那里继续取决于你发现了什么。
回答by Roger Rowland
You don't show the database schema, but from looking at the SQL it seems that the first field is numberic (idClient
) and you are trying to use this with ListBox.AddItem
, which expects a string.
您没有显示数据库架构,但从查看 SQL 看来,第一个字段似乎是数字 ( idClient
) 并且您试图将其与 一起使用ListBox.AddItem
,它需要一个字符串。
So, you just have to convert as follows:
因此,您只需按如下方式进行转换:
With UserForm2.ListBox1
.AddItem Str(rs(1))
' etc. ....
End With