【问题标题】:<Excel-VBA> "Type mismatch" error while copying value from cell into textbox<Excel-VBA> 将值从单元格复制到文本框时出现“类型不匹配”错误
【发布时间】:2017-04-19 02:01:11
【问题描述】:

我目前正在做一个简单的用户表单工作表数据编辑界面,位于同一个工作簿中。我的用户表单按钮在工作表 A 上,而数据库(从中提取数据)在另一个工作表中。我目前正在研究搜索功能(包含在下面的整个代码块),并且在以下行遇到“类型不匹配”错误:

MsgBox ws.Range("B" + cRow).Value

我已经尝试使用 CVar() 和其他替代方法,但它不能解决问题。

我的预期工作流程是,当用户在“txtCompany”文本框中输入公司名称并单击搜索按钮时,它将在“公司名称”(D 列)列中的数据库中搜索相似名称并返回该行中的所有其他值到我的用户表单中的文本框。

如果有人能告诉我是什么导致了这个问题,我将不胜感激。 Sub 的完整代码如下:

Private Sub btnSearch_Click()

Dim lRow As Long
Dim ws As Worksheet
Dim srcterm As String
Dim datevalue As String
Dim cCol, cRow As Integer

Set ws = ThisWorkbook.Worksheets("Database")
lRow = ws.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row

Dim x As Control
For Each x In frmSearch.Controls
    If TypeName(x) = "TextBox" Then
    x.Value = ""
    End If
Next x

srcterm = txtCompany.Value
MsgBox lRow

For Each cell In ws.Range("D3:D" & lRow)

    If cell.Value Like srcterm Then

        cRow = cell.Row
        MsgBox cRow
        MsgBox ws.Range("B" + cRow).Value

        With frmSearch
            .txtDate.Value = ws.Range("B" + cRow).Value
            .txtCustomer.Value = ws.Cells("C" + cRow).Value
            .txtCompany.Value = ws.Cells("D" + cRow).Value
            .txtAddress.Value = ws.Cells("E" + cRow).Value
            .txtContact.Value = ws.Cells("F" + cRow).Value
            .txtEmail.Value = ws.Cells("G" + cRow).Value
            .txtStatus.Value = ws.Cells("H" + cRow).Value
        End With

        datevalue = ws.Cells("A" + cRow).Value
    End If

Next cell

End Sub

【问题讨论】:

  • MsgBox 的必需参数是一个字符串,所以你不想使用 cVar(),而是使用 cStr() 或 Format()。值是否可能为空?
  • 我添加了以下行(这应该是我的预期结果)并且值正确返回,所以我猜该值不应该为空? MsgBox ws.Range("B3").Value
  • 好吧,我花了一段时间才注意到...而不是 ("B" + cRow),使用 ("B" & cRow)。其他地方也一样。 & 是字符串连接运算符,而不是 +。
  • @RichHolton 非常感谢!是的,按照 A.S.H 的建议做了,效果很好! :D
  • 很高兴 A.S.H.能够比我早看到它。

标签: vba excel search


【解决方案1】:

"B" + cRow

这不是在 VBA 中将数字连接到字符串的方式。你应该使用:

"B" & cRow
'  ^^^

好的,+ 运算符适用于连接字符串,即"a" + "b",但在字符串和数字上尝试它时,这是一个类型不匹配。您可以使用 "B" + CStr(cRow),但我建议您完全放弃使用 + 运算符在 VBA 中进行字符串连接,并在此问题上坚持使用 &amp; 运算符。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多