当CLng具有文本字符串时,运行时错误13不匹配

时间:2017-01-15 19:35:40

标签: excel excel-vba runtime-error vba

我非常擅长excel vba,我想问一下如何更改此代码以修改H3:H7单元格(1,2,3,4,5)到(1F,2F,3F) ,4F,5F)使宏工作?

如果我尝试将例如H3单元格的值修改为" 1F"我得到"运行时错误' 13':类型不匹配"因为我猜下面的第一个代码无法处理文本字符串但是我应该如何修改代码?

 returnedNumber = CLng(words(iWord, 2)) // How should I modify to handle number and text string too?

Excel Sheet (Screenshot)

Option Explicit
Private Sub CommandButton3_Click()
Dim cell As Range
Dim words As Variant
Dim word As String, number As Long

words = Range("H3", Cells(Rows.Count, "G").End(xlUp)).Value

For Each cell In Range("J3", Cells(Rows.Count, "J").End(xlUp)).SpecialCells(xlCellTypeConstants, xlTextValues)
    If FindWord(cell.Value, words, word, number) Then
        cell.Offset(, 3).Resize(, 2).Value = Array(word, number)
    End If
Next
End Sub
Function FindWord(sentence As String, words As Variant, returnedWord As String, returnedNumber As Long) As Boolean
Dim iWord As Long
Dim word As String

For iWord = LBound(words, 1) To UBound(words, 1)
    word = CStr(words(iWord, 1))
    If InStr(sentence, word) Then
        FindWord = True
        returnedWord = word
        returnedNumber = CLng(words(iWord, 2))
        Exit Function
    End If
Next
End Function

1 个答案:

答案 0 :(得分:0)

要允许值为"1F"等文字,您需要

  • returnedNumber As Long更改为returnedNumber As String
  • CLng(words(iWord, 2))更改为CStr(words(iWord, 2))
  • number As Long更改为number As String