问题
I have two workbooks, one with the Code INSIDE of it Sheet1 (which is the codename of the sheet I want to copy values from) and another workbook defined as "y" in this example. I want to copy over the values of cell "K1-K10" in Sheet1 into cell ("F1-F10") of workbook y (For example, I want F1.Value=K1.Value, F2.Value = K2.Value, etc...).
Both workbooks are protected with a password, I am only trying to copy values from Sheet1 (that is why I don't unprotect it), but I want to save, close and protect workbook "y" once all of the values copy and paste into it.
When I hit the Activex Commandbutton inside Sheet1, the code is freezing up my workbook. I have double checked the file paths and the sheet names as well, they are correct.
I have also posted screenshots of the code and both workbooks below:
Private Sub CommandButton1_Click()
Dim y As Workbook
Dim i As Integer
Set y = Workbooks.Open(Filename:="\\FILEPATH\Test 2.xlsm", Password:="Swarf")
With y
For i = 1 To 10
Do While Cells(i, 11).Value <> ""
.Sheets("MyTest2").Unprotect "Swarf"
.Sheets("Mytest2").Cells(i, 6).Value = Sheet1.Cells(i, 11).Value
Loop
Next i
.Password = "Swarf"
.Save
.Close False
End With
End Sub
回答1:
Do need use While Loop
for this case.
Use If
will be solved your issue.
Private Sub CommandButton1_Click()
Dim y As Workbook
Dim i As Integer
Set y = Workbooks.Open(Filename:="\\FILEPATH\Test 2.xlsm", Password:="Swarf")
With y
For i = 1 To 10
If (Cells(i, 11).Value <> "") Then
.Sheets("MyTest2").Unprotect "Swarf"
.Sheets("Mytest2").Cells(i, 6).Value = Sheet1.Cells(i, 11).Value
End If
Next i
.Password = "Swarf"
.Save
.Close False
End With
End Sub
Because you will cause infinity loop for your while loop
statement.
For example: i=1
,then the statement Cells(i, 11).Value <> ""
always return true and continue looping.
回答2:
There is no need to loop, you can just transfer the information of the complete range in one go something like:
With y
.Sheets("MyTest2").Unprotect "Swarf"
.Sheets("Mytest2").Range("F1:F10").Value = Worksheets("Sheet1").Range("K1:K10").Value
End With
There are plenty of posts on SO about finding the last row of a column if you really have a problem copying empty cells
来源:https://stackoverflow.com/questions/59110114/running-a-for-loop-with-a-nested-do-while-statement-but-why-is-my-code-freezing