加速VB.NET应用程序到Excel

时间:2015-07-29 10:50:48

标签: arrays vb.net excel visual-studio-2015

我在Visual Studio 2015中编写了一个VB.NET应用程序。(第一次与visual basic或VS有任何联系)。应用程序接受输入csv文件,对其进行分析并根据该分析将其拆分为2个输出csv文件。对于其中一个输出文件,我需要将每个空白单元格更改为零值。我的问题是,我所做的代码是处理750个输入csv文件以生成1500个输出文件,并且循环中的每个进程花费5分钟意味着它需要最多5天才能运行!!太长了!

我正试图弄清楚如何让代码更快地运行。一个简单的第一步是在空白单元格到零操作,因为我目前正逐个单元地进行操作。我通过数组阅读更好,但我不确定如何编码...有人可以帮忙吗?

我的代码现在是:

    Dim forceDataRangeDest, cell As Excel.Range
    Dim blank As String
    Dim forceDataRow, lastDataRow As Integer

'copy force data from original workbook to sheet 1 of new workbook
            If ws.Range("Z" & (forceLegRowStart + 1)).Value = "Force Plate 3" Then
                forceDataRow = forceDataRow + 2
                forceDataRangeSrc = ws.Range("Z" & forceDataRow & ":AK" & lastDataRow)
            Else forceDataRangeSrc = ws.Range("A" & forceDataRow & ":M" & lastDataRow)
            End If
            wsData = wbForce.Sheets("Sheet1")
            wsData.Name = "Data"
            forceDataRangeDest = wsData.Range("A1")
            forceDataRangeSrc.Copy(forceDataRangeDest)

            'insert new column A if Force Plate 3 data is one taken for the time interval data of column A
            If ws.Range("Z" & (forceLegRowStart + 1)).Value = "Force Plate 3" Then
                wsData.Columns("A:A").Insert(1)
                'write in the Data
                forceDataRangeSrc = ws.Range("A" & forceDataRow & ":A" & lastDataRow)
                forceDataRangeSrc.Copy(wsData.Range("A1"))
            End If

    forceDataRangeDest = wsData.Range("A1:M" & ((lastDataRow - forceDataRow) + 1))
                For Each cell In forceDataRangeDest
                    blank = cell.Value
                    If String.IsNullOrWhiteSpace(blank) Then
                        cell.Value = 0
                    End If
                Next

这个示例代码底部的For Each单元格,我认为实际上是在增加处理时间...我如何将其作为数组写入,然后一次性将数组写入excel?

非常感谢您提供任何帮助。

1 个答案:

答案 0 :(得分:0)

您可以在VBA中使用Range.FindRange.FindNext方法,这比循环遍历所有单元格更快。这是VBA代码的一个示例:

Sub FindEmptyCells()

Dim found As Range
Dim firstCell As String

    Set found = ActiveSheet.UsedRange.Find(What:="", LookAt:=xlWhole)
    firstCell = found.Address

    Do While Not (found Is Nothing)
        Debug.Print found.Address
        Set found = ActiveSheet.UsedRange.FindNext(found)
        If found.Address = firstCell Then
            Exit Do
        End If
    Loop

End Sub

编辑:添加了使用OP范围对象的代码

Dim found As Range
Dim firstCell As String

    Set found = forceDataRangeDest.Find(What:="", LookAt:=xlWhole)
    firstCell = found.Address

    Do While Not (found Is Nothing)
        found.Value = 0
        Set found = forceDataRangeDest.FindNext(found)
        If found.Address = firstCell Then
            Exit Do
        End If
    Loop