不久前我遇到了同样的问题。如果我没记错的话,它会中断,因为查询仍然想访问具有不同名称的东西。我不知道为什么重命名查询时 Excel 不会更改引用。如果您通过右键单击手动重命名它,它甚至不会自动更改它。如果您查看查询,右键单击它,然后切换到属性或中间选项卡的名称,您可以看到一些详细信息。
长话短说,这就是我修复我的方法:
Sub Create_new_connection()
'On Error Resume Next
'Count the current amount of queries and save that number to refer to it later
QueryCount = ThisWorkbook.Queries.Count
'Copy the template and rename it
ThisWorkbook.Sheets("Template").Copy after:=ThisWorkbook.Sheets("Template")
ThisWorkbook.Sheets(3).Name = "Put a name here"
'Change the name of the query
ThisWorkbook.Queries.Item(QueryCount + 1).Name = "New Query Name"
'Change the names of the new table
ThisWorkbook.Sheets(3).ListObjects(1).Name = "I had a table I wanted to rename"
'Change the formula of the new connection
NewFormula = Replace(ThisWorkbook.Queries.Item(1).Formula, ThisWorkbook.Sheets("Create New List").ListObjects("Template").DataBodyRange(1, 1), ThisWorkbook.Sheets("Create New List").ListObjects("FAUF").DataBodyRange(1, 1))
ThisWorkbook.Queries.Item(QueryCount + 1).Formula = NewFormula
'Connect the new table to the new connection and
ThisWorkbook.Sheets(3).ListObjects(1).QueryTable.WorkbookConnection = "Abfrage - " & ThisWorkbook.Queries.Item(QueryCount + 1).Name
ThisWorkbook.Sheets(3).ListObjects(1).QueryTable.Connection = "OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=" & """" & ThisWorkbook.Queries.Item(QueryCount + 1).Name & """" & ";Extended Properties=" & """" & """"
ThisWorkbook.Sheets(3).ListObjects(1).QueryTable.CommandText = "SELECT * FROM [" & ThisWorkbook.Queries.Item(QueryCount + 1).Name & "]"
'Refresh the new connection
ThisWorkbook.Sheets(3).ListObjects(1).QueryTable.Refresh BackgroundQuery:=False
End Sub
倒数第二组,修改连接的 3 个是重要的。这是在德语 Excel 上,因此您可能需要更改“Abfrage -”位以适合您的语言。正确更改WorkbookConnection、Connection 和CommantText 非常重要。