在Excel VBA中为宏添加书签

时间:2014-05-06 08:21:05

标签: excel vba bookmarks

我是VBA的新手,所以我想知道是否有人可以帮助我一直在努力的事情。这是一个相当简单的概念,我相信大多数概念都是在一个我似乎无法开始工作的功能之外完成的。

到目前为止,我已经创建了一个书签功能,其中突出显示当前选定的一个或多个单元格,并将范围命名为' bookmark'第一次调用VBA脚本。通过使用VBA脚本,第二次围绕用户从先前突出显示的单元格中取出,并删除范围名称和突出显示。但是,此功能仅适用于一个工作簿及其中的相应工作表。

我希望能够将此功能用于所有当前打开的工作簿或特定文件夹中的所有excel文档。我的代码如下:

Sub setBookmark()

    Dim rRangeCheck As Range
    Dim myName As Name

    On Error Resume Next
    Set rRangeCheck = Range("bookmark")
    On Error GoTo 0
    If rRangeCheck Is Nothing Then

        ThisWorkbook.Names.Add "bookmark", Selection
        With Selection.Interior
            .Pattern = xlSolid
            .PatternColorIndex = xlAutomatic
            .Color = 65535
            .TintAndShade = 0
            .PatternTintAndShade = 0
        End With
    Else
        Application.Goto Range("bookmark")

        With Selection.Interior
            .Pattern = xlNone
            .TintAndShade = 0
            .PatternTintAndShade = 0
        End With

        For Each myName In ThisWorkbook.Names
            If myName.NameLocal = "bookmark" Then myName.Delete
        Next
    End If

End Sub

1 个答案:

答案 0 :(得分:0)

像这样修改:

Dim rRangeCheck
Dim myName As Name

On Error Resume Next
rRangeCheck = ""
rRangeCheck = Application.Names("bookmark")
On Error GoTo 0
If rRangeCheck = "" Then

    ActiveWorkbook.Names.Add "bookmark", Selection
    With Selection.Interior
        .Pattern = xlSolid
        .PatternColorIndex = xlAutomatic
        .Color = 65535
        .TintAndShade = 0
        .PatternTintAndShade = 0
    End With
Else
    Application.Goto Range("bookmark")
    Application.Goto Range("bookmark")

    With Selection.Interior
        .Pattern = xlNone
        .TintAndShade = 0
        .PatternTintAndShade = 0
    End With

    For Each myName In ActiveWorkbook.Names
        If myName.NameLocal = "bookmark" Then myName.Delete
    Next
End If

双重Applicatio.Goto它是选择工作簿+表格和单元格......
如果删除,则仅删除它所选择的工作簿。