【问题标题】:Delete unwanted queries in VBA删除 VBA 中不需要的查询
【发布时间】:2019-11-01 04:20:01
【问题描述】:

如何从工作簿中删除所有不需要的查询?

Sub DeleteQuery()
    Dim queries As Variant
    queries = Array("q1", "q2", "q3")
    For Each qr In ThisWorkbook.queries
        'Not sure about the syntax of the following line
        If qr not in queries Then
        qr.Delete
    Next qr
End Sub

如果查询不在列表中,则应将其删除

ActiveWorkbook.Queries("Query1").Delete

不起作用,因为不需要的查询的名称不清楚

【问题讨论】:

  • 嗨,看看这个答案:stackoverflow.com/questions/44827417/…
  • 嗨,谢谢。但它仍然假设不需要的查询名称是已知的
  • 那么真正的问题是什么?我认为If qr not in queries Then 的事实不会起作用,因为qr.Delete 的语法很好

标签: excel vba


【解决方案1】:

您需要遍历查询,然后遍历整个数组以查找匹配项,如果不存在匹配项,则删除。

Sub testingPQ()

    Dim vQuery As Variant
    Dim arrQueries() As Variant
    Dim i As Long

    arrQueries = Array("q1", "q2", "q3")


    For Each vQuery In ThisWorkbook.Queries
        'loop through array to check for each query
        For i = LBound(arrQueries) To UBound(arrQueries)
            If vQuery.Name = arrQueries(i) Then
                'do not delete
                Exit For
            End If
            If i = UBound(arrQueries) Then
                'delete - no match
                vQuery.Delete
            End If
        Next i
    Next vQuery

End Sub

【讨论】:

  • @JvdV 对,已更新,未正确阅读 OP 帖子。这样就可以了。
  • @BigBen 在内存中工作应该没问题。不在内存中工作时反对它。 :)
  • If i = UBound(arrQueries) - 不确定这是否真的有效。如果匹配发生在i 怎么办?
  • ^ 同意。也许如果您将数组放入字典/数组列表并检查名称是否为.Exists,那么这是避免IsError 和第二个循环的好方法。但是,@BigBen 使用方式中的IsError 也是合法的。
  • 呃抱歉忽略 - Double For 循环让我失望。这就是为什么...我支持字典的想法。
【解决方案2】:

您可以在查询名称中使用Application.Match

If IsError(Application.Match(qr.Name, queries, 0)) Then ' query name is not in list

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-20
    • 1970-01-01
    • 2014-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多