无法获取字符类的text属性

时间:2016-01-04 21:35:33

标签: excel vba excel-vba

这是我正在VBA工作的excel 2010宏的摘录,我遇到的问题是DelStrikethroughs

每当单元格中的值为“TRUE”,“FALSE”或“#N / A”时(当宏的“#N / A”崩溃时),该函数返回一个空字符串。经过进一步调查后,变量x.text看起来总是空白的,当我尝试调试它时会出现错误"Unable to get the text property of the characters class"

有关如何解决此问题的任何想法? (我很高兴函数返回原始文本,如果它不能删除文本中的删除,但首选的是正确的解决方案)

以下是代码示例:

Sub testx()
    Dim testRange As Range
    Set testRange = selection
    Call DelStrikethroughs(testRange.Cells(1, 1))
End Sub


Function DelStrikethroughs(Cell As Range) As String
    'Returns the text value of a cell with strikethrough characters removed
    Dim NewText As String
    Dim iCh As Integer
    For iCh = 1 To Len(Cell)
        Dim x As Characters
        Set x = Cell.Characters(iCh, 1)
        On Error Resume Next '"On Error" is here to deal with blank characters
            If x.Font.Strikethrough = False Then
                NewText = NewText & x.text
            End If
        If Err.Number = 0 Then
            NewText = NewText
        Else
            NewText = NewText & x.text
        End If
    Next iCh
    DelStrikethroughs = NewText
End Function

2 个答案:

答案 0 :(得分:1)

试试这个:

Sub testx()
    Dim testRange As Range, c As Range
    Set testRange = Selection
    For Each c In testRange
        c.Offset(0, 1).Value = DelStrikethroughs(c)
    Next c
End Sub


Function DelStrikethroughs(Cell As Range) As String
    'Returns the text value of a cell with strikethrough characters removed
    Dim NewText As String
    Dim iCh As Long, l As Long, ch As Characters

    On Error Resume Next
    l = Cell.Characters.Count
    On Error GoTo 0

    If l = 0 Then
        NewText = Cell.Text
    Else
        For iCh = 1 To l
            Set ch = Cell.Characters(iCh, 1)
            NewText = NewText & IIf(ch.Font.Strikethrough, "", ch.Text)
        Next iCh
    End If
    DelStrikethroughs = NewText
End Function

答案 1 :(得分:0)

如果您要做的只是返回单元格中没有任何删除线的文本,请尝试:

Function DelStrikethroughs(Cell As Range) As String
   DelStrikethroughs = Cell.Text
End Function