简体   繁体   中英

unable to get the text property of the characters class, no change to line causing error

I have a sub that will be passed a column letter, and for row 2 to the last row of that column, extract only the numbers from the cells and overwrite the cells with those numbers.`

Sub ExtractNumbersInColumn(ColWithNums As String)

Dim Rng As Range, Dn As Range, nStr As String, n As Long
Dim wb As Workbook
Dim ws As Worksheet

Set wb = ThisWorkbook
Set ws = wb.Sheets("RefindData")

Dim rngStart As Range
Dim rngEnd As Range

Set rngStart = ws.Range(ColWithNums & "2")
Set rngEnd = ws.Range(ColWithNums & Rows.Count).End(xlUp)
Set Rng = ws.Range(rngStart, rngEnd)

For Each Dn In Rng

For n = 1 To Len(Dn.Value)
    If Dn.Characters(n, 1).Text Like "[0-9]" Then
        nStr = nStr & Dn.Characters(n, 1).Text
    End If
Next n

Dn = Val(nStr): nStr = ""

Next Dn

End Sub`

I am getting an issue with this line:

 If Dn.Characters(n, 1).Text Like "[0-9]" Then

with the error - "unable to get the text property of the characters class"

After doing a little research this problem appears with older versions of Excel. I am using 2003. However, the simplified version of this code:

  Sub MG31May23
Dim Rng As Range, Dn As Range, nStr As String, n As Long
Set Rng = Range(Range("A1"), Range("A" & Rows.Count).End(xlUp))
For Each Dn In Rng
For n = 1 To Len(Dn.Value)
    If Dn.Characters(n, 1).Text Like "[0-9]" Then
        nStr = nStr & Dn.Characters(n, 1).Text
    End If
Next n
Dn.Offset(, 1) = Val(nStr): nStr = ""
Next Dn
End Sub

Works fine, and that particular line is not changed.

Any ideas?

EDIT:

I have discovered that it does not like to look at a cell containing only numbers otherwise .Text will kick up a fuss. So the real question now is how can I alter this for it to be happy looking at cells that contain letters and numbers, as well as just numbers (but not do anything with obviously)

With help from the commenters, this section of code works better to perform the task of number extraction:

   For n = 1 To Len(Dn.Value)
    If IsNumeric(Mid(Dn.Value, n, 1)) Then
        nStr = nStr & Mid(Dn.Value, n, 1)
    End If
Next n

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM