如何优化此vba循环代码?

时间:2011-05-24 13:37:11

标签: optimization vba

您好我写了这段代码。但是这段代码很慢。如何优化此代码?

Private Sub printItem(r, lastCol, objStream)
    FirstCol = 1

    Dim strFirst As String

    strFirst = CStr(ActiveSheet.Cells(r, 1).Value)

    If strFirst = "" Then
        Exit Sub
    End If

        objStream.WriteText "    <"
        objStream.WriteText "TagName"
        objStream.WriteText " "

        For c = FirstCol To lastCol

            data = CStr(ActiveSheet.Cells(r, c).Value)

            If LenB(Trim$(data)) > 0 Then
                objStream.WriteText g_AttributeName(c)
                objStream.WriteText "="""
                objStream.WriteText data
                objStream.WriteText """ "
            End If

        Next c

        objStream.WriteText "/>"

    objStream.WriteText vbNewLine
End Sub

1 个答案:

答案 0 :(得分:4)

这可能是您的代码速度缓慢的原因:您正在遍历单元格。 VBA和Excel工作表数据之间的每次通信都会产生很大的开销,当您一次引用一个单元格时,这会增加。

相反,您应该将所有数据一次加载到Variant数组中,然后遍历该数组,如下所示。这明显更快。

    Dim varData As Variant

    varData = ActiveSheet.Cells(r, FirstCol).Resize(1, lastCol - FirstCol + 1)

    For c = LBound(varData, 2) To UBound(varData, 2)

        data = CStr(varData(1, c))

        If LenB(Trim$(data)) > 0 Then
            ' etc.
        EndIf

    Next c

如需进一步阅读,请查看这篇旧的但仍然相关的文章:http://www.avdf.com/apr98/art_ot003.html