你如何使VBA在多个单元格上运行?

时间:2013-11-11 19:44:33

标签: excel-vba vba excel

我对VBA很新,但对公式非常擅长。我正在制定时间戳问题。我编写了代码,这样如果我从E3中的验证列表中选择,它将在F3中给我一个时间戳。我希望从E3开始的E列中的所有单元格都是如此。我将有500到15000条记录(行)。我正在使用的代码粘贴在下面。提前感谢任何建议。

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

2 个答案:

答案 0 :(得分:3)

这是怎么回事?

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

答案 1 :(得分:0)

最快的方法是选择整个范围,使用数组设置值一次。这是在.Value包含多个单元格的Range属性时完成的。

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