Wednesday, April 24, 2019

Avoiding Select in VBA Excel macros with variable ranges

The errors are probably being caused by the Copy and PasteSpecial lines in this block of code:




        With S
.SL.Copy

End With
With R
.RL.PasteSpecial
End With



Once you have Set a range variable, Excel knows which worksheet and which workbook contains that range variable. If you want to do something to the range then you do not need to include the worksheet. So, in your code, you just use



SL.Copy

RL. PasteSpecial


It is always a good idea to think if you have any code inside a loop that should be outside. In your code you Set your worksheet variables within the loop but this should be done once before the loop. Adding in the comments made to your post, your code should be changed to:



Dim S As Worksheet
Dim R As Worksheet
Set R = Sheets("Front")
Set S = Sheets("CHECK LIST")


Counter2 = 17
For Counter1 = 12 To 150

Dim SL As Range
Dim RL As Range
Set SL = S.Range(S.Cells(Counter1, 1), S.Cells(Counter1, 10))
Set RL = R.Range(R.Cells(Counter2, 1), R.Cells(Counter2, 10))

Set curCell = Worksheets("CHECK LIST").Cells(Counter1, 6)
Set checkCell = Worksheets("Front").Cells(3, 5)

If curCell.Value = checkCell.Value Then

SL.Copy
RL.PasteSpecial

Counter2 = Counter2 + 1
End If
Next Counter1



The PasteSpecial method has several parameters:



.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, SkipBlanks:=False, _
Transpose:=False


If you are not using these, then maybe you can do a "normal" copy & paste?



SL.Copy RL

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...