VBA 코드로 PQ를 리프레시할 때마다 쿼리가 복제되는 이유가 뭘까용...
원본 쿼리는 그대로 있고 한 번 리프레시할 때마다 연결 전용 쿼리가 원본쿼리 (2) 원본쿼리 (3) 식으로 무한 증식됩니다....
쿼리 갱신 코드:
Function RefreshQueryTableSafely(tableName As String) As Boolean
On Error GoTo Fail
Dim tbl As ListObject
Set tbl = ThisWorkbook.Sheets("시트이름").ListObjects(tableName)
tbl.QueryTable.Refresh BackgroundQuery:=False
RefreshQueryTableSafely = True
Exit Function
Fail:
RefreshQueryTableSafely = False
End Function
안녕하세요~
질문에서 언급한 문제는,
이 코드로 인해,
VBA로 ListObject.QueryTable.Refresh를 반복 호출할 때,
Excel이 해당 QueryTable을 “새 연결”로 인식하는 경우가 있을 수 있는데,
그 결과, Excel이 기존 쿼리를 덮어쓰지 않고
자동으로 새로운 이름(원본쿼리 (2), 원본쿼리 (3) …)을 만들어버립니다.
특히,
BackgroundQuery := False를 이용해 강제로 동기식 리프레시를 반복할 때
자주 발생할 수 있습니다.
일단,
리프레시전에
Sub 연결상태진단() Dim conn As WorkbookConnection For Each conn In ThisWorkbook.Connections Debug.Print "━━━━━━━━━━━━━━━━━━━━━━" Debug.Print "연결 이름: " & conn.Name Debug.Print "타입: " & conn.Type If conn.Type = xlConnectionTypeOLEDB Then Debug.Print "BackgroundQuery: " & _ conn.OLEDBConnection.BackgroundQuery Debug.Print "RefreshOnFileOpen: " & _ conn.OLEDBConnection.RefreshOnFileOpen End If Next conn End Sub연결상태를 진단하고,
쿼리명과 타입을 확인합니다.
그리고
아래와 같이 코딩을 하고
Function RefreshPowerQuerySafely(queryName As String) As Boolean On Error GoTo ErrorHandler Dim conn As WorkbookConnection Dim connName As String '// 1. 먼저 WorkbookQuery가 존재하는지 확인 On Error Resume Next connName = ThisWorkbook.Queries(queryName).Name On Error GoTo ErrorHandler If connName = "" Then Debug.Print " 쿼리를 찾을 수 없음: " & queryName RefreshPowerQuerySafely = False Exit Function End If '// 2. WorkbookConnection을 통해 안전하게 리프레시 For Each conn In ThisWorkbook.Connections If conn.Name = queryName Then '// 2-1. BackgroundQuery 강제 비활성화 (중복 방지) If conn.Type = xlConnectionTypeOLEDB Or _ conn.Type = xlConnectionTypeODBC Then conn.OLEDBConnection.BackgroundQuery = False End If '// 리프레시 실행 conn.Refresh Debug.Print " 리프레시 완료: " & queryName RefreshPowerQuerySafely = True Exit Function End If Next conn '// 3. 연결이 없으면 쿼리만 리프레시 (Connection-only 쿼리) ThisWorkbook.Queries(queryName).Refresh Debug.Print " 쿼리만 리프레시: " & queryName RefreshPowerQuerySafely = True Exit Function ErrorHandler: Debug.Print " 오류 발생: " & Err.Description RefreshPowerQuerySafely = False End Function
이렇게 테스트해 보세요.
Sub 테스트() If RefreshPowerQuerySafely("표1") Then MsgBox "리프레시 성공!", vbInformation Else MsgBox "리프레시 실패. 로그를 확인하세요.", vbCritical End If End Sub감사합니다. 알고 보니 로드된 표를 다른 곳에 복사하는 과정에서 xlPasteAll을 쓴 게 문제였습니다. 답변 정말 감사합니다!!