'Incrementing a Number Sequence in a Dynamic Table
I have a procedure called TableNumberSequence that adds a table row, pauses for a second and then adds another. It does this up until what's specified in the code, which is < 9.
At the moment, the rows are blank. The problem is I don't know how to generate a number sequence from 1 to 8 to populate the rows.
I know how to do this with a For Each loop outside a table, but doing it inside one is giving me a headache.
Sub TableNumberSequence()
Dim tbl As ListObject
Dim rng As Range
Dim n As Integer
Set tbl = Worksheets("Sheet1").ListObjects("Table1")
Set rng = tbl.ListColumns("Number").DataBodyRange
Call DeleteAllRows
n = 1
Do While n < 9
Call IntervalTime
n = n + 1
Call AddRow
Loop
End Sub
These additional procedures are called in the main one.
Sub AddRow()
Dim ws As Worksheet
Dim tbl As ListObject
Set ws = Worksheets("Sheet1")
Set tbl = ws.ListObjects("Table1")
tbl.ListRows.Add
End Sub
Sub DeleteAllRows()
With Range("Table1").ListObject
If Not .DataBodyRange Is Nothing Then
.DataBodyRange.Delete
End If
End With
End Sub
Sub IntervalTime()
Dim target As Date
target = Now + TimeValue("00:00:" & Range("Interval").Text)
Do
DoEvents
Loop Until Now >= target
End Sub
Solution 1:[1]
EDIT - Here's a full tested version:
Sub TableNumberSequence()
Dim tbl As ListObject
Dim n, sec As Double
sec = Range("Interval").Value 'use a number here
Set tbl = Worksheets("Sheet3").ListObjects("Table1")
DeleteAllRows tbl 'remove rows
For n = 1 To 8
AddRow tbl, n
IntervalTime sec
Next n
End Sub
'add a row and place `id` in the first cell
Sub AddRow(tbl As ListObject, id)
tbl.ListRows.Add.Range.Cells(1).Value = id
End Sub
'remove any rows from listobject `tbl`
Sub DeleteAllRows(tbl As ListObject)
If Not tbl.DataBodyRange Is Nothing Then tbl.DataBodyRange.Delete
End Sub
'wait for `sec` seconds
Sub IntervalTime(sec As Double)
Dim t
t = Timer
Do While Timer - t < sec
DoEvents
Loop
End Sub
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
