如何提高follownig代码的效率

时间:2015-09-04 02:27:53

标签: excel vba excel-vba optimization

任何人都可以帮我优化以下简单代码 完成执行需要永远。 也许我正在某个地方遇到无限循环。 如果它们相等则它只需要两个字符串然后根据这里提到的单元格来改变位置。

 Sub sort()

 Dim astid As String
 Dim partno As String
 Dim FinalRow As Long
 Dim i, j As Integer

 FinalRow = Sheets("Combined Version").Range("H9000").End(xlUp).Row

 For i = 5 To FinalRow

    partno = Sheets("Combined Version").Cells(i, 7).Value

    For j = 5 To FinalRow

       astid = Sheets("Combined Version").Cells(j, 8).Value

        If astid = partno Then

            Cells(j, 8).Select
            Selection.Copy
            Range("N5").Select
            ActiveSheet.Paste

            Cells(i, 8).Select
            Application.CutCopyMode = False
            Selection.Copy
            Cells(j, 8).Select
            ActiveSheet.Paste

            Range("N5").Select
            Application.CutCopyMode = False
            Selection.Copy
            Cells(i, 8).Select
            ActiveSheet.Paste

        End If

    Next j
Next i
End Sub

2 个答案:

答案 0 :(得分:2)

看起来您正在扫描工作表中每一行的每一行!这可以通过Find进一步改进,该FindAll选择列中匹配的所有单元格,然后您只需枚举它们。查看Chip Pearson的Sub sort() Dim astid As String Dim partno As String Dim FinalRow As Long Dim i, j As Integer Dim Cell_I As String Dim Cell_J As String Dim ws As Worksheet 'Don't update the screen until the end Application.ScreenUpdating = False Set ws = Sheets("Combined Version") FinalRow = ws.Range("H9000").End(xlUp).Row For i = 5 To FinalRow partno = ws.Cells(i, 7).Value For j = 5 To FinalRow astid = ws.Cells(j, 8).Value If astid = partno Then Cell_I = ws.Cells(i, 8).Value Cell_J = ws.Cells(j, 8).Value ws.Cells(j, 8).Value = Cell_I ws.Cells(i, 8).Value = Cell_J End If Next j Next i Set ws = Nothing Application.ScreenUpdating = True End Sub 函数以获取相关帮助。 http://www.cpearson.com/excel/FindAll.aspx

此外,您正在不必要地使用剪贴板。在进行切换时,您只需要在变量中保存值。

试试这个(使用与没有优化的“FindAll”选项相同的结构): -

root/folder

答案 1 :(得分:2)

由于您已将值存储在 astid var中,因此不必使用iterim N5作为临时保留区域。

Sub mysort()
    Dim astid As String, partno As String
    Dim fr As Long, i, j As Long

    With Sheets("Combined Version")
        fr = .Cells(Rows.Count, "H").End(xlUp).Row
        For i = 5 To fr
            partno = .Cells(i, 7).Value2
            For j = 5 To fr
                astid = .Cells(j, 8).Value2
                If LCase(astid) = LCase(partno) Then
                    .Cells(j, 8) = .Cells(i, 8).Value2
                    .Cells(i, 8) = astid
                End If
            Next j
        Next i
    End With
End Sub

With ... End With statement的使用减少了重复调用以识别工作表。

使用变体数组可以更快地实现这一点。