访问VBA - 更快地更改大范围内的Excel单元格值?

时间:2013-04-19 17:08:28

标签: excel vba ms-access excel-vba

我在Access中有一些VBA代码,它从Excel工作表中获取一系列单元格,然后将它们从数字转换为日期。例如,范围是H1:Y25000

Public Sub FixDates(theRange as Range)

Dim RangeCell as Range

For Each RangeCell In theRange
    If IsNumeric(RangeCell.Value) And RangeCell.Value > 0 And Not IsEmpty(RangeCell.Value) Then
        lngDate = CLng(RangeCell.Value)
        RangeCell.Value = DateAdd("d", lngDate -1, "1/1/1968")
    End If
Next RangeCell

End Sub

代码似乎有效,但运行时间可能很长。这可以用不同的方式写得更快吗?我正在阅读使用Variant而不是Range,但我无法弄明白。

哦,要打电话给Sub,我会使用类似的东西:

path = "C:\myfile.xlsx"
Set xlApp = CreateObject("Excel.Application")
Set xlWbk = xlApp.Workbooks.Open(path)
Set xlWks = xlWbk.Worksheets(1)
lastRow = xlWks.Range("A1").End(xlDown).Row
FixDates (xlWks.Range("H1:Y" & lastRow))

谢谢!

1 个答案:

答案 0 :(得分:6)

您可以简单地将范围分配给变量,这将创建一个数组 - 它看起来像下面的代码 - 您应该添加适当的错误处理:

Public Sub FixDates(theRange as Range)

    Dim data as Variant
    Dim i as Long
    Dim j as Long
    Dim lngDate as Long

    data = theRange

    For i = LBound(data, 1) to UBound(data, 1)
        For j = LBound(data, 2) to UBound(data, 2)
            If IsNumeric(data(i, j)) Then
                If data(i, j) > 0 Then
                    lngDate = CLng(data(i, j))
                    data(i, j) = DateAdd("d", lngDate - 1, "1/1/1968")
                End If
            End If
        Next j
    Next i

    theRange = data

End Sub