Option Explicit
Public Sub Rename_Web_Query_Sheets()
Dim ws As Worksheet
Dim qt As QueryTable
Dim qtArray() As String, qtArrayLen As Long
Dim r As Long, n As Long
Dim foundIndex As Long
'Create array of all web queries for fast searching
qtArrayLen = 0
For Each ws In ActiveWorkbook.Worksheets
For Each qt In ws.QueryTables
Debug.Print qt.Connection, qt.Destination.Worksheet.Name, qt.Destination.Address
qtArrayLen = qtArrayLen + 1
ReDim Preserve qtArray(1 To 2, 1 To qtArrayLen)
qtArray(1, qtArrayLen) = qt.Connection
qtArray(2, qtArrayLen) = qt.Destination.Worksheet.Name
Next
Next
MsgBox "Active workbook = " & ActiveWorkbook.Name & vbCrLf & "Number of web queries = " & qtArrayLen
Debug.Print "qtArrayLen = " & qtArrayLen
Debug.Print qtArray(1, 1), qtArray(2, 1)
Debug.Print qtArray(1, 2), qtArray(2, 2)
With ActiveWorkbook.Worksheets("List")
For r = 2 To .Cells(.Rows.Count, "B").End(xlUp).Row
'Search array for sheet containing query connection in column D
Debug.Print r, .Cells(r, "D").Value
foundIndex = 0
n = 1
While n <= UBound(qtArray, 2) And foundIndex = 0
Debug.Print n, qtArray(1, n), qtArray(2, n)
If InStr(qtArray(1, n), .Cells(r, "D").Value) Then foundIndex = n
n = n + 1
Wend
If foundIndex <> 0 Then
'Rename found sheet
Debug.Print "found " & qtArray(1, foundIndex), qtArray(2, foundIndex)
If MsgBox(.Name & " sheet row : " & r & vbCrLf & "Web query connection : " & .Cells(r, "D").Value & vbCrLf & "Found in sheet : " & qtArray(2, foundIndex) & vbCrLf & vbCrLf & _
"Rename sheet " & qtArray(2, foundIndex) & " as " & .Cells(r, "B").Value & "?", vbInformation + vbYesNo, "Web query found") = vbYes Then
ActiveWorkbook.Worksheets(qtArray(2, foundIndex)).Name = .Cells(r, "B").Value
End If
Else
'Sheet not found
MsgBox .Name & " sheet row : " & r & vbCrLf & "Web query connection not found for " & .Cells(r, "D").Value, vbExclamation, "Web query not found"
End If
Next
End With
End Sub