简体   繁体   English

宏遍历工作簿中的所有工作表

[英]Macro to Loop Through All Worksheets in a Workbook

I have a task to make the replacement of hyperlinks in 1000 files to a new server. 我的任务是将1000个文件中的超链接替换为新服务器。 I already have a working script for replacing hyperlinks, but it only works on the active page. 我已经有一个用于替换超链接的工作脚本,但是它仅在活动页面上有效。 Tell me how to make it go through all the pages in the book. 告诉我如何使它遍及本书中的所有页面。

Sub changeLinks()

Const oldPrefix = "\\oldServer\common"
Const newPrefix = "\\NewServer\common"
Dim h As Hyperlink, oldLink As String, newLink As String

For Each h In ActiveSheet.Hyperlinks
    'this will change Address but not TextToDisplay
    oldLink = h.Address
    Debug.Print "Found link: " & oldLink
    If Left(oldLink, Len(oldPrefix)) = oldPrefix Then
            newLink = newPrefix & Right(h.Address, Len(h.Address) - Len(oldPrefix))


            h.Address = newLink
            Debug.Print "  Changed to " & h.Address
    End If
Next h

End Sub

Call your routine in a loop : 循环调用例程:

Sub ProcessAllSheets()
    Dim s As Worksheet
    For Each s In Sheets
        Call changeLinks(s.Name)
    Next s
End Sub

With these changes to your routine: 对您的常规进行以下更改:

Sub changeLinks(s As String)

Const oldPrefix = "\\oldServer\common"
Const newPrefix = "\\NewServer\common"
Dim h As Hyperlink, oldLink As String, newLink As String

For Each h In Sheets(s).Hyperlinks
    'this will change Address but not TextToDisplay
    oldLink = h.Address
    Debug.Print "Found link: " & oldLink
    If Left(oldLink, Len(oldPrefix)) = oldPrefix Then
            newLink = newPrefix & Right(h.Address, Len(h.Address) - Len(oldPrefix))


            h.Address = newLink
            Debug.Print "  Changed to " & h.Address
    End If
Next h
End Sub

Throw a loop around your hyperlink loop to iterate through each sheet. 在您的超链接循环周围抛出一个循环,以遍历每个工作表。

Sub changeLinks()
    Dim objSheet As Worksheet

    Const oldPrefix = "\\oldServer\common"
    Const newPrefix = "\\NewServer\common"
    Dim h As Hyperlink, oldLink As String, newLink As String

    For Each objSheet In ThisWorkbook.Sheets
        For Each h In objSheet.Hyperlinks
            'this will change Address but not TextToDisplay
            oldLink = h.Address

            Debug.Print "Found link: " & oldLink

            If Left(oldLink, Len(oldPrefix)) = oldPrefix Then
                newLink = newPrefix & Right(h.Address, Len(h.Address) - Len(oldPrefix))
                h.Address = newLink
                Debug.Print "  Changed to " & h.Address
            End If
        Next h
    Next
End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM