Home » excel » excel vba – How do you make VBA run on multiple cells?

excel vba – How do you make VBA run on multiple cells?

Posted by: admin May 14, 2020 Leave a comment

Questions:

I am very new to VBA but pretty good at formulas. I am working on a time stamp issue. I have the code written so that if I choose from a validation list in E3 it will give me a time stamp in F3. I want this to be true of all cells in the E column starting with E3. I will have between 500 and 15000 records (rows). The code I am using is pasted below. Thanks in advance for any suggestions.

Private Sub Worksheet_Change(ByVal Target As Range)
  If Target.Column = 5 And Target.Row = 3 Then
    If Target.Value = "" Then
      Cells(3, 6).Value = ""
    Else
      Cells(3, 6).Value = Format(Now, "mm/dd/yyyy HH:mm:ss")
    End If
  End If
End Sub
How to&Answers:

How’s this?

Private Sub Worksheet_Change(ByVal Target As Range)
  If Target.Column = 5 And Target.Row >= 3 Then
  i = Target.Row
    If Target.Value = "" Then
  Cells(i, 6).Value = ""
Else
  Cells(i, 6).Value = Format(Now, "mm/dd/yyyy HH:mm:ss")
End If
 End If
End Sub

Answer:

The fastest way to do this is to select the entire range a set the value once using an array. This is done with the .Value property of a Range when it contains multiple cells.

Private Sub SetDate(ByVal Target As Range, Optional bybal RowCount as Long = 0)
    Dim i as Long
    ' Check if row count needs to be found
    If RowCount = 0 Then
        'Count non-empty rows from target down
        RowCount = Target.Worksheet.Range(Target, Target.End(xlDown).Rows.Count
    End If
    ' Target entire range of cells that are going to be affected
    Set Target = Target.Resize(RowCount, 6)
    Dim vals() as Variant 
    ' Read values from worksheet
    vals = Target.Values        
    ' Make changes in memory here
    For i=1 to RowCount
        if IsEmpty(vals(i,1)) Then
            vals(i, 6) = vbNullString
        Else
            vals(i, 6) = Format(Now, "mm/dd/yyyy HH:mm:ss")
        End If
    Next i
    ' Write values into worksheet
    Target.Value = vals
End Sub