热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

加快VBA代码运行速度更快-SpeedingupVBACodetoRunFaster

IhaveanExcelWorkbookwheretheuserimportsatextfilebytheclickofabutton.Mycodeworks

I have an Excel Workbook where the user imports a text file by the click of a button. My code works exactly as I need it to but it is extremely slow when filling in column H, Reading Date. Here is what my Excel Workbook looks like when the text file has been imported to the excel sheet: enter image description here

我有一个Excel工作簿,用户通过单击按钮导入文本文件。我的代码完全按照我的需要工作,但填写H列,阅读日期时速度非常慢。以下是将文本文件导入Excel工作表时Excel工作簿的外观:

Here is my code:

这是我的代码:

Sub Import_Textfiles()
Dim fName As String, LastRow As Integer

Worksheets("Data Importation Sheet").Activate

LastRow = Range("A" & Rows.Count).End(xlUp).Row + 1
    ' Finds the first blank row to import text file data to
fName = Application.GetOpenFilename("Text Files (*.txt), *.txt")

If fName = "False" Then Exit Sub

  With ActiveSheet.QueryTables.Add(Connection:="TEXT;" & fName, _
        Destination:=Range("A" & LastRow))
        .Name = "2001-02-27 14-48-00"
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen= False
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = False
        .RefreshPeriod = 0
        .TextFilePromptOnRefresh= False
        .TextFilePlatform = 437
        .TextFileStartRow = 2
        .TextFileParseType = xlFixedWidth
        .TextFileTextQualifier = xlTextQualifierDoubleQuote
        .TextFileCOnsecutiveDelimiter= False
        .TextFileTabDelimiter = True
        .TextFileSemicolOnDelimiter= False
        .TextFileCommaDelimiter = False
        .TextFileSpaceDelimiter = False
        .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1)
        .TextFileFixedColumnWidths = Array(14, 14, 8, 16, 12, 14)
        .TextFileTrailingMinusNumbers = True
        .Refresh BackgroundQuery:=False
    End With
    ActiveWindow.SmallScroll Down:=0


    Dim strShortName As String


    'Adding Reading Date to Excel Sheet:
    Dim rowCount As Integer, currentRow As Integer
    Dim sourceCol As Integer, nextCol As Integer
    Dim currentRowValue As String
    Dim fileDate1 As String
    Dim fileDate2 As String

    sourceCol = 1 'columnA
    nextCol = 8 'column H
    rowCount = Cells(Rows.Count, sourceCol).End(xlUp).Row

    strShortName = fName
    fileDate1 = Mid(fName, InStrRev(fName, "\") + 1)
    fileDate2 = Left(fileDate1, 10)

    Cells(LastRow, 9) = ("Updating Location: " & strShortName)

    For currentRow = 1 To rowCount
        currentRowValue = Cells(currentRow, nextCol).Value
        If currentRowValue = "" Then
        Cells((currentRow), (nextCol)).Select
        Cells((currentRow), (nextCol)) = fileDate2
        End If
    Next

End Sub

If anyone has any suggestions as to how I can speed up the importation of the reading date I would appreciate it greatly! Thanks in advance!

如果有人对如何加快阅读日期的输入有任何建议,我将非常感激!提前致谢!

3 个解决方案

#1


2  

Few things that I noticed

我注意到的事情很少

  1. As mentioned by Chris in comments, you can turn off screen updating and set calculation to manual and switch them back on and set calculation to automatic at the end of the code.
  2. 正如Chris在评论中所提到的,您可以关闭屏幕更新并将计算设置为手动并重新打开它们,并在代码结束时将计算设置为自动。

For Example

With Application
    .ScreenUpdating = False
    .Calculation = xlCalculationManual
End With

'
'~~> Rest of your code
'
With Application
    .ScreenUpdating = True
    .Calculation = xlCalculationAutomatic
End With
  1. Avoid the use of .Select. it reduces the speed of the code. You do not need to select the cell to write to it.
  2. 避免使用.Select。它降低了代码的速度。您无需选择要写入的单元格。

Your For Loop can be written as.

你的For循环可以写成。

For currentRow = 1 To RowCount
    If Cells(currentRow, nextCol).Value = "" Then
        Cells(currentRow, nextCol).Value = fileDate2
    End If
Next

This it self will increase the speed of your code as you are not selecting the cell anymore before writing to it.

这样它会增加代码的速度,因为在写入之前你不再选择单元格了。

  1. Ideally I would copy the range to an array and then do what you are doing with the array and then write it back to the cell but then that is me.

    理想情况下,我会将范围复制到数组,然后执行您对数组执行的操作,然后将其写回单元格,但那就是我。

  2. Remove unnecessary lines of code. ActiveWindow.SmallScroll Down:=0 is not needed.

    删除不必要的代码行。 ActiveWindow.SmallScroll Down:= 0不需要。

  3. Work with object(s) and fully qualify your object(s).

    使用对象并完全限定对象。

  4. When working with Excel rows, use Long instead of Integer

    使用Excel行时,请使用Long而不是Integer

#2


0  

Try this:

Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Application.EnableEvents = False

YOUR CODE HERE

Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Application.EnableEvents = True

#3


0  

The best solution depends on a few things, that aren't clear to me from provided data. The following change will speed it up a lot (selecting cells takes a lot of time), but its not the optimum. If its still to slow, please provide ~ number of rows and ~% of rows (in column H), that are filled before you get to the following code. Then either searching for missing values or (probably in most cases) copying column H into an array and copying back after updating the values will do the trick.

最好的解决方案取决于一些事情,我提供的数据并不清楚。以下更改将加速它(选择单元格需要花费很多时间),但它不是最佳的。如果它仍然变慢,请提供〜行数和〜%行(在H列中),在您到达以下代码之前填充这些行。然后搜索缺失值或(可能在大多数情况下)将列H复制到数组中并在更新值之后复制回来将起到作用。

Old code:

For currentRow = 1 To rowCount
    currentRowValue = Cells(currentRow, nextCol).Value
    If currentRowValue = "" Then
    Cells((currentRow), (nextCol)).Select
    Cells((currentRow), (nextCol)) = fileDate2
    End If
Next

New code:

For currentRow = 1 To rowCount
    if Cells(currentRow, nextCol).Value = "" then
        Cells(currentRow,nextCol).Value = fileDate2
    End If
Next

推荐阅读
author-avatar
三人行
做出色的电商媒介平台:给兼职者免费给单,不要押金保证金,在家就可以工作,做一单结算一单,结算快!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有