Excel VBA打印单元格中即时窗口的结果

时间:2017-03-24 09:54:18

标签: excel vba excel-vba

我有一个宏,用于计算每个查询运行多长时间并将时间输出到即时窗口。

我有办法将其设置为输出到单元格吗?

宏:

Sub TimeQueries()
    Dim oSh As Worksheet
    Dim oCn As WorkbookConnection
    Dim dTime As Double
    For Each oCn In ThisWorkbook.Connections
        dTime = Timer
        oCn.Ranges(1).ListObject.QueryTable.Refresh False
        Debug.Print Timer - dTime, oCn.Name, oCn.Ranges(1).Address(external:=True)
    Next
End Sub

立即窗口输出:

 6.609375     Query1        [YEtest.xlsm]Query1!$A$1:$S$3006
 15.12109375  Query2        [YEtest.xlsm]Query2!$A$1:$S$3006
 21.0703125   Query3        [YEtest.xlsm]Query3!$A$1:$S$3006
 0.125        Query4        [YEtest.xlsm]Query4!$A$1:$B$2

标签名称我希望它输出到:Control

3 个答案:

答案 0 :(得分:2)

只需将oSh设置为工作表参考,然后使用Cells集合输出您想要的内容:

Sub TimeQueries()
    Dim oSh As Worksheet
    Dim oCn As WorkbookConnection
    Dim dTime As Double
    Dim lngCounter As Long

    'set a worksheet reference - e.g. Sheet1
    Set oSh = ThisWorkbook.Worksheets("Control")

    'initialise counter
    lngCounter = 1
    For Each oCn In ThisWorkbook.Connections
        dTime = Timer
        oCn.Ranges(1).ListObject.QueryTable.Refresh False

        'set output to cells on the worksheet
        oSh.Cells(lngCounter, 1).Value = Timer - dTime
        oSh.Cells(lngCounter, 2).Value = oCn.Name
        oSh.Cells(lngCounter, 3).Value = oCn.Ranges(1).Address(external:=True)
        lngCounter = lngCounter + 1

        'Debug.Print Timer - dTime, oCn.Name, oCn.Ranges(1).Address(external:=True)
    Next
End Sub

答案 1 :(得分:2)

Sub TimeQueries()
    Dim oSh As Worksheet
    Dim oCn As WorkbookConnection
    Dim dTime As Double
    Dim rw As Long

    rw = 1
    For Each oCn In ThisWorkbook.Connections
        rw = rw + 1
        dTime = Timer
        oCn.Ranges(1).ListObject.QueryTable.Refresh False
        With Sheets("Control")
            .Cells(rw, 1) = Timer - dTime
            .Cells(rw, 2) = oCn.Name
            .Cells(rw, 3) = oCn.Ranges(1).Address(external:=True)
        End With
    Next
End Sub

答案 2 :(得分:1)

这应该有效:

Sub TimeQueries()
    Dim oSh As Worksheet
    Dim oCn As WorkbookConnection
    Dim dTime As Double

    'define first output range
    Dim rng as Range
    Set rng = ThisWorkbook.Worksheets("Control").Range("A1:C1") 'change as necessary

    For Each oCn In ThisWorkbook.Connections
        dTime = Timer
        oCn.Ranges(1).ListObject.QueryTable.Refresh False

        'output to defined range and then redefine rng to the row below
        rng.Value = Array(Timer - dTime, oCn.Name, oCn.Ranges(1).Address (external:=True))
        Set rng = rng.Offset(1,0)
    Next
End Sub