我的代码无法满足我的要求,如何对其进行优化? VBA

时间:2019-06-28 13:50:52

标签: excel vba performance

我有一个程序,该程序可以读取数千行并返回所需的值。问题在于,即使是在保存代码时,请求也要花费大量时间(例如1分钟)来搜索并粘贴值,

我认为代码很慢:

If Sheets("MT950").Cells(line, 1) Like "-}{5:*" Then

这是我的代码:

Function mysolde62(mycurrency As String, swift As String) As Double

Dim SearchString As String
Dim LastLine As Long, line As Long, k As Long
Dim mybegin As Long, myend As Long, test As Long, count As Long
Dim sign As String
Dim myvalue As Double

LastLine = Sheets("MT950").Range("A1").End(xlDown).Row

count = 0
myend = 1

For line = 1 To LastLine

If Sheets("MT950").Cells(line, 1) Like "-}{5:*" Then

    SearchString = Sheets("MT950").Range("A" & line).Value

    mypos = InStr(1, SearchString, swift, 1)
    If mypos <> 0 Then
        count = count + 1
    End If

End If
Next line

For k = 1 To count

For line = myend To LastLine
    If Sheets("MT950").Cells(line, 1) Like "-}{5:*" Then
        SearchString = Sheets("MT950").Range("A" & line).Value

        mypos = InStr(1, SearchString, swift, 1)
        If mypos <> 0 Then

            mybegin = line
            For linebis = mybegin To LastLine
                If Sheets("MT950").Cells(linebis, 1) Like ":62F:*" Then
                    SearchString = Sheets("MT950").Range("A" & linebis).Value

                    mypos = InStr(1, SearchString, mycurrency, 1)
                    If mypos <> 0 Then
                        myend = linebis
                        test = 1
                    End If
                    Exit For
                End If
            Next linebis

            If test = 1 Then Exit For
        End If
    End If
Next line
If test = 1 Then Exit For
Next k


sign = Mid(Sheets("MT950").Cells(myend, 1).Value, 5, 1)
myvalue = Mid(Sheets("MT950").Cells(myend, 1).Value, 15)
If sign = "D" Then
mysolde62 = -myvalue
Else
mysolde62 = myvalue
End If


End Function

1 个答案:

答案 0 :(得分:0)

免责声明:我不是Excel开发人员,因此不熟悉Excel对象。

对于VBA / VB6,通常:尽可能避免使用数据类型Variant和函数的Variant版本。因此,使用Mid $()代替Mid(),使用Left $()代替Left()等等。在您的代码中像这样:

sign = Mid(Sheets("MT950").Cells(myend, 1).Value, 5, 1)

这应该读

sign = Mid$(Sheets("MT950").Cells(myend, 1).Value, 5, 1)

有关VB6 / VBA的常规优化技巧,请在此处查看:https://www.aivosto.com/articles/stringopt.html

那是说,我想您发现了什么是罪魁祸首。 Like运算符比其他运算符慢。现在,看一下代码,似乎您正在搜索以<-> {5:“开始的行,然后以”:62F:“开头的行。如果是这种情况,请代替

If Sheets("MT950").Cells(line, 1) Like "-}{5:*" Then

使用类似

' Validate the first 5 characters
If Left$(Sheets("MT950").Cells(line, 1), 5) = "-}{5:" Then