Excel VBA prints direct window results in cell (s)
I have a macro in which how many times each request is executed to start and output the time to the nearest window.
Is there a way to set it to output to cells?
Macro:
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
Direct window output:
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
Tab name I want it to be displayed on: Control
+3
source to share
3 answers
Just oSh
link to the worksheet and use the collection Cells
to output what you want:
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
+2
source to share
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
source to share
This should work:
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
+1
source to share