整个工作簿中的上标(R) - VBA

时间:2016-02-17 10:35:28

标签: excel vba

我有一个包含10-15张的Excel工作簿,在整个工作簿中我有许多注册商标符号,在单元格中键入文本(显示为®)。我需要一个可以遍历所有单元格内容的宏,找到该单元格的那一部分的®和上标。

我已经在下面草拟了一个草稿,但是我得到了一个'对象变量或者没有设置块变量'错误。

Sub Superscript()
    Application.ScreenUpdating = False
    Dim sht As Worksheet
    For Each sht In Worksheets
    sht.Activate
    Dim Match As Variant, start As Variant, pos As Long, cnt As Integer
    With ActiveSheet
        Set Match = .Cells.Find("®", LookIn:=xlValues, lookat:=xlPart)    ' Find the first match in the active sheet
        If Not Match Is Nothing Then
            start = Match.Address
            Do
               cnt = Len(Match.Value) - Len(WorksheetFunction.Substitute(Match.Value, "®", ""))
               pos = InStr(Match.Value, "®")
            Do
                Match.Characters(pos, 1).Font.Superscript = True
                pos = InStr(pos + 1, Match.Value, "®")
                cnt = cnt - 1
               Loop While cnt > 0
               Set Match = .Cells.FindNext(Match)
            Loop While Not Match Is Nothing And Match.Address <> start
        End If
    End With
    Next sht
    Application.ScreenUpdating = True
End Sub

1 个答案:

答案 0 :(得分:1)

一旦您确定已找到某些内容,您就无法从Range.Find method获得任何内容,除非您更改内容以使查找不再找到它。您实际上并没有更改内容,只是修改格式。对地址的检查是为了确保你没有经历所有的比赛并最终回到你最终会做的事情,但是.Find永远不会是什么。

Sub Superscript()
    Dim sht As Worksheet
    Dim fnd As Range, frst As String, pos As Long, cnt As Integer

    For Each sht In Worksheets
        With sht
            Set fnd = .Cells.Find(Chr(174), LookIn:=xlValues, lookat:=xlPart)    ' Find the first match in the active sheet
            If Not fnd Is Nothing Then
                frst = fnd.Address
                Do
                    pos = InStr(1, fnd.Value, Chr(174))
                   Do
                        fnd.Characters(start:=pos, Length:=1).Font.Superscript = True
                        pos = InStr(pos + 1, fnd.Value, Chr(174))
                   Loop While pos > 0
                   Set fnd = .Cells.FindNext(after:=fnd)
                Loop While fnd.Address <> frst
            End If
        End With
    Next sht

End Sub

我不希望看到与保留字同名的变量,所以我也对var名称进行了一些表面的修改。