excelvbarangerowrtd

Dynamic RTD Data Recording to Another Sheet


This code works fine when the data is presented from a range of C4:C7 column however my worksheet is setup with data in a row from C4:K4. I can't get a row instead of a column to work out. Any help? Thanks view pic with issue.

Sub RecordData()
Dim Interval As Double
Dim cel As Range, Capture As Range
Interval = 30 'Number of seconds between each recording of data
Set Capture = Worksheets("Sheet1").Range("C4:K4") 'Capture this row of data
With Worksheets("Sheet2") 'Record the data on this worksheet
    Set cel = .Range("A2") 'First timestamp goes here
    Set cel = .Cells(.Rows.Count, cel.Column).End(xlUp).Offset(1, 0)
    cel.Value = Now
    cel.Offset(0, 1).Resize(1, Capture.Cells.Count).Value = Application.Transpose(Capture.Value)
End With
NextTime = Now + Interval / 86400
Application.OnTime NextTime, "RecordData"
End Sub

Solution

  • Transposing Capture.Value is the problem; you don't need to do this, since both the destination and source ranges have the same shape.

    Suggestion: avoid referring to worksheets by the name they display on their tab in Excel. These names typically change over time and will cause your code to break. For example, With Worksheets("Sheet2")... will fail with error 9 "Subscript out of range" as soon as you change Sheet2's name to something else.

    You can give a stable, "internal" name to a worksheet, and directly use it in VBA code, as long as said VBA code resides in the same workbook as the worksheet. The worksheet property I am referring to is called CodeName. You can set it from the Visual Basic editor by clicking on the worksheet in the Project Explorer, then assigning to the (Name) property in the Properties Window, as shown below, where I've given the CodeName "SourceWs" to a worksheet named "Source Worksheet" as seen from Excel:

    enter image description here

    Then, your code could be rewritten as:

    Option Explicit
    
    Sub RecordData()
        Dim Interval As Double
        Dim cel As Range, Capture As Range
        Dim NextTime As Date
    
        Interval = 30 'Number of seconds between each recording of data
    
        Set Capture = SourceWs.Range("C4:K4") 'Capture this row of data
    
        With DestWs 'Record the data on this worksheet
            Set cel = .Range("A2") 'First timestamp goes here
            Set cel = .Cells(.Rows.Count, cel.Column).End(xlUp).Offset(1, 0)
            cel.Value = Now
            cel.Offset(0, 1).Resize(1, Capture.Cells.Count).Value = Capture.Value
        End With
    
        NextTime = Now + Interval / 86400
        Application.OnTime NextTime, "RecordData"
    End Sub
    

    As for your question about training videos, try googling excel mvp blog and you'll find more than you can handle. Have fun.