替换文本时如何处理多个活动单元格

时间:2018-06-20 23:02:02

标签: excel vba excel-vba

我正在寻找即时修改单元格文本的方法。 例如:“ n”,“ N”或“新” --->“新”

我已经开始工作了,但是当我选择多个单元格来删除文本时遇到了问题。

有人可以帮助我确定如何实现此目标,并且仍然能够修改多个excel单元格值(删除是我唯一关心的问题,除非您能想到我的代码可能引起的其他限制)。

-只是为了澄清,我的代码将按我希望的方式更改文本,但是,当我选择多个单元格并按Delete键(以删除单元格的值)时,我得到Range()的类型不匹配Target.Address).Value

感谢大家的宝贵时间, 铝

Private Sub Worksheet_Change(ByVal Target As Range)

    Dim OriginalText As String
    Dim CorrectedText As String
        OriginalText = Range(Target.Address).Value
        If OriginalText = "r" Or OriginalText = "R" Or OriginalText = "replace" Then
           CorrectedText = "Replace"
           Range(Target.Address).Value = CorrectedText
        ElseIf OriginalText = "a" Or OriginalText = "A" Or OriginalText = "acceptable" Then
            CorrectedText = "Acceptable"
           Range(Target.Address).Value = CorrectedText
        ElseIf OriginalText = "n" Or OriginalText = "N" Or OriginalText = "new" Then
            CorrectedText = "New"
           Range(Target.Address).Value = CorrectedText
        End If

End Sub

更新: 我不能告诉你我有多感谢每个人的慷慨!谢谢您的帮助。我希望这也可以帮助其他有需要的人。 干杯Al

2 个答案:

答案 0 :(得分:0)

使用区域:

Dim area,cell as range
For each area in target.areas
    For each cell in area.cells
        OriginalText = cell.value
    next
next

答案 1 :(得分:0)

类似这样的东西:

Private Sub Worksheet_Change(ByVal Target As Range)

    Dim c As Range, newText As String, v

    'exit if too many cells (eg whole column)
    If Target.CountLarge > 1000 Then Exit Sub

    For Each c In Target.Cells
        v = c.Value
        Select Case v
            Case "r", "R", "replace": newText = "Replace"
            Case "a", "A", "acceptable": newText = "Acceptable"
            Case "n", "N", "new": newText = "New"
            Case Else: newText = v
        End Select
        If newText <> v Then
            Application.EnableEvents = False
                c.Value = newText
            Application.EnableEvents = True
        End If
    Next c

End Sub