无法获取字符类的text属性,没有更改为行导致错误

时间:2017-05-31 21:38:11

标签: excel vba excel-vba

我有一个子列,它将传递一个列字母,而第二行传递给该列的最后一行,只提取单元格中的数字并用这些数字覆盖单元格。

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`

我对这一行有疑问:

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

错误 - "无法获取字符类"

的text属性

进行一些研究后,旧版本的Excel会出现此问题。我正在使用2003.但是,此代码的简化版本:

  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

工作正常,并且不会更改该特定行。

有什么想法吗?

编辑:

我发现它不喜欢看一个只包含数字的单元格,否则.Text会大惊小怪。所以现在真正的问题是我如何改变这一点,因为它很高兴看到包含字母和数字的单元格,以及只是数字(但显然没有做任何事情)

1 个答案:

答案 0 :(得分:0)

在评论者的帮助下,这段代码可以更好地执行数字提取任务:

   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