VBA: Copy specific cells from sheet to another based on a value in a cell

lunatu

Board Regular
Joined
Feb 5, 2021
Messages
77
Office Version
  1. 2010
Platform
  1. Windows
  2. Web
Hi,

Im trying to run a very basic code but something is wrong with it.
Im want to copy cells B:G from sheet1 to sheet2 if there is text "close" in sheet1 column M.

My current code below is working but it also copies the cells where value in column M is something else than "close". Any ideas what gap I am having in my code?

VBA Code:
Sub CopyWon()

Dim LR As Long, i As Long
With Sheets("Sheet1")
 LR = .Range("M" & Rows.Count).End(xlUp).Row
 For i = 1 To LR
 
 If .Range("M" & i).Value = "close" Then
 dlr = Sheets("Sheet2").Cells(Rows.Count, "A").End(xlUp).Row + 1
.Range("B" & i).Resize(2, 6).Copy Destination:=Sheets("Sheet2").Range("A" & dlr)
    End If
    Next i
End With
 End Sub
 

Excel Facts

VLOOKUP to Left?
Use =VLOOKUP(A2,CHOOSE({1,2},$Z$1:$Z$99,$Y$1:$Y$99),2,False) to lookup Y values to left of Z values.
I think the issue lies here in the range you are copying:
Rich (BB code):
.Range("B" & i).Resize(2, 6)
The "Resize" command is expanding your selection to multiple rows (instead of just the row meeting the conditions).
Is that what you are really intending to do?

See here for an explanation of "Resize": Resize Property in Excel VBA
 
Upvote 0
Solution
I think the issue lies here in the range you are copying:
Rich (BB code):
.Range("B" & i).Resize(2, 6)
The "Resize" command is expanding your selection to multiple rows (instead of just the row meeting the conditions).
Is that what you are really intending to do?

See here for an explanation of "Resize": Resize Property in Excel VBA
Oh yes I had left that one there! Deleting that reisize everything is working again. Thanks for your help :)
 
Upvote 0
You are welcome.
 
Upvote 0

Forum statistics

Threads
1,215,032
Messages
6,122,770
Members
449,095
Latest member
m_smith_solihull

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top