Search code examples
excelvbaloopsfor-loopdo-loops

Improving the speed of a Loop's performance?


I currently have to workbooks, Test 1 (the name of the first workbook where the code is written) and Test 2 (where values are pasted into from Test 1). My current code takes the values from Rows K1-K10 (Column 11, Rows 1-10) from the Test 1 workbook and pastes them into Columns F2-P2 (Row 2, Columns 6-16) of the Test 2 workbook (THE FIRST CODE IS WORKING).

I am trying to make this code run faster as when I use it for my other applications, I feel as if the loop makes it laggy and sluggish. I am trying to replace the Do (While) Loop with a Double (For) Loop statement. Please let me know if you have a suggestion as my Double (For) Loop is not pasting any values into the Test 2 workbook (Also how do I measure the time it takes for each function to run).

Here are both codes and screenshots as well for visual aid:

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

Here is my attempted code at a Double (for) Loop:


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


Solution

  • To much code to write in a comment, but here you go:

    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
    

    Not sure about the Protect / Password thing.