提高循环性能的速度?

Improving the speed of a Loop's performance?

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

我正在努力使这个代码运行更快,因为当我将它用于我的其他应用程序时,我感觉好像循环使它变得迟钝和缓慢。我正在尝试用 Do (While) Loop双(For)循环语句。如果您有任何建议,请告诉我,因为我的 Double (For) Loop 没有将任何值粘贴到 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

这是我在双(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

要在评论中写的代码太多了,但是你开始吧:

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

不确定保护/密码的事情。

这是 @Vincent G 稍作修改的答案(我接受了他的答案)- 刚刚修复了我收到的密码错误,我现在正在使用这段代码并且它正在运行完美无瑕!

把这篇文章留在这里以防其他人阅读这篇文章post并想知道每个人的建议的最终结果是什么,感谢所有做出贡献的人。

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