提高循环的执行速度?

时间:2019-12-04 15:48:05

标签: excel vba loops for-loop do-loops

我目前必须工作簿,测试1 (编写代码的第一个工作簿的名称)和测试2 (其中将值从粘贴到其中) >测试1 )。我当前的代码从 Test 1 工作簿的第K1-K10行(第11列,第1-10行)中获取值,并将其粘贴到 F2-P2列中(测试2 工作簿(第一个代码正在工作)的第2行(第6-16列)

我正试图使此代码运行得更快,就像我将其用于其他应用程序时一样,我感觉好像循环使它变得缓慢而缓慢。我正在尝试使用 Double(For)循环语句 替换 执行(同时)循环 。如果您有建议,请告诉我,因为我的 Double(For)循环 没有将任何值粘贴到 Test 2 工作簿中(我要测量每个功能运行所花费的时间。

以下是代码和屏幕截图,也可以提供视觉帮助:

Private Sub CommandButton1_Click()

Dim y As Workbook
Dim i As Integer
Dim j As Integer
i = 6
j = 1

Set y = Workbooks.Open(Filename:="\\FILEPATH\Databases\Test 2.xlsm", Password:="Swarf")

    With y



        Do While j <= 11
            If (Cells(j, 11).Value <> "") Then

                .Sheets("MyTest2").Unprotect "Swarf"
                .Sheets("Mytest2").Cells(2, i).Value = Sheet1.Cells(j, 11).Value

            End If

        i = i + 1
        j = j + 1

        Loop



        .Password = "Swarf"
        .Save
        .Close False

    End With


End Sub

这是我在Double(for)循环中尝试的代码:


Private Sub CommandButton1_Click()

Dim y As Workbook
Dim i As Integer
Dim j As Integer

Set y = Workbooks.Open(Filename:="\\FILEPATH\Databases\Test 2.xlsm", Password:="Swarf")

    With y

        For i = 6 To 16
          For j = 1 To 10


            If (Cells(i, 11).Value <> "") Then

                .Sheets("MyTest2").Unprotect "Swarf"
                .Sheets("Mytest2").Cells(2, i).Value = Sheet1.Cells(j, 11).Value

            End If

          Next j
        Next i

        .Password = "Swarf"
        .Save
        .Close False

    End With


End Sub

enter image description here

enter image description here

enter image description here

enter image description here

2 个答案:

答案 0 :(得分:2)

要在注释中写很多代码,但是您可以这样做:

Private Sub CommandButton1_Click()

    With Workbooks.Open(Filename:="\\FILEPATH\Databases\Test 2.xlsm", Password:="Swarf").Sheets("MyTest2")
        .Unprotect "Swarf"
        .Range("F2:O2") = Application.Transpose(Sheet1.Range("K1:K10"))
        .Protect "Swarf"
        .Password = "Swarf"
        .Save
        .Close False
    End With
End Sub

不确定“保护/密码”问题。

答案 1 :(得分:0)

这是 @Vincent G 的答案(我已经接受了他的答案)-已稍作修改-刚刚解决了我遇到的密码错误,我现在正在使用此代码,并且可以正常工作!

在此感谢其他人的贡献,以防其他人读这篇文章,并想知道每个人的建议的最终结果是什么。

Private Sub CommandButton1_Click()

Dim y As Workbook

Application.ScreenUpdating = False

Set y = Workbooks.Open(Filename:="\\FILEPATH\Databases\Test 2.xlsm", Password:="Swarf")

    With y
        Sheets("MyTest2").Unprotect "Swarf"

        .Sheets("Mytest2").Range("F2:O2") = Application.Transpose(Sheet1.Range("K1:K10"))

        Password = "Swarf"
        .Save
        .Close False

    End With

Application.ScreenUpdating = True

End Sub