QueryTable无法赋值给对象变量的VBA问题求助
QueryTable无法赋值给对象变量的问题求助
为提升VBA基础能力,我购买了Bill Jelen和Tracy Syrstad所著的《Microsoft Excel VBA and Macros》,在学习第18章内容时,遇到QueryTable无法赋值给对象变量的问题。
我编写的对应书中18.4节的Worksheet_SelectionChange子程序如下:
Private Sub Worksheet_SelectionChange(ByVal Target As Range) Dim id As String Dim ThisArtist As String Dim ThisAlbum As String Dim qtArtistAlbums As QueryTable Dim qtAlbumTracks As QueryTable If Target.Cells.Count = 1 Then If Target.Column <= 3 Then If Target.Row > 3 Then ThisArtist = Cells(Target.Row, 1).Value If Trim(ThisArtist) <> "" Then id = "ArtistAlbums" Set qtArtistAlbums = ActiveSheet.ListObjects(id).QueryTable If Not qtArtistAlbums.Refreshing Then ThisWorkbook.Queries(id).Formula = "let Result = " & "fnGetAlbums(""" & ThisArtist & """) in Result" qtArtistAlbums.Refresh False Application.Goto Range("E4") End If End If End If ElseIf Target.Column >= 4 And Target.Column <= 7 Then If Target.Row > 3 Then ThisAlbum = Cells(Target.Row, 5) If Trim(ThisAlbum) <> "" Then id = "AlbumTracks" Set qtAlbumTracks = ActiveSheet.ListObjects(id).QueryTable If Not qtAlbumTracks.Refreshing Then ThisWorkbook.Queries(id).Formula = "let Result =" & "fnGetTracks(""" & ThisAlbum & """) in Result" qtAlbumTracks.Refresh False Application.Goto Range("J5") End If End If End If End If End If End Sub
代码执行到If Not qtArtistAlbums.Refreshing Then或If Not qtAlbumTracks.Refreshing Then时出错,Intellihints显示qt相关变量为Nothing,说明赋值语句未成功获取QueryTable对象。
我在18.3节中使用类似语句Set qtSearchArtist = ThisWorkbook.Worksheets("Sheet1").ListObjects(id).QueryTable可正常运行,但将该写法移植到当前代码中仍无效。
我还在工作簿模块中编写了测试子程序:
Private Sub test() Dim id As String Dim sheet As Worksheet Dim lo As ListObject Dim qt As QueryTable Set sheet = ThisWorkbook.Sheets("Sheet1") id = "ArtistAlbums" Set lo = sheet.ListObjects(id) Set qt = lo.QueryTable Debug.Print (qt.Name) End Sub
修改Set lo = sheet.ListObjects(id)为Set lo = Range(id).ListObject后,仍无法成功将QueryTable赋值给qt变量。
恳请提供排查思路与解决方案。
内容的提问来源于stack exchange,提问作者user27558355
相关产品推荐
相关产品推荐

