I'm having problems making copy/pasting clean. Currently I have this:
If distanceValue <= distanceParameter Then
sh2.Rows(i).Copy _
sh3.Rows(i).Offset(0, 1)
End If
sh2 and sh3 are properly defined and it's inside a for loop; that's not the problem. Range seems messy to use, as I would have to define a lastcolumn variable, etc. Is there anyway to do this with .Rows?
The goal is to copy a row if it meets the condition to another sheet but leaving column A blank. Any feedback on clean solutions (I know this one is wrong) would be greatly appreciated.
Your copy range (if you copy the entire row) will be larger then your paste range if you offset by a column. You can't paste 16384 columns into 16383, not enough room.
If you do not wish to use the range function, you will have to copy the entire rows then add a column to the front.
Or you could add the column to the source data before the copy paste, removing the columns when finished if needed.
Sub Sample()
Dim sh2 As Worksheet, sh3 As Worksheet
Set sh2 = Worksheets("Sheet1")
Set sh3 = Worksheets("Sheet2")
If distanceValue <= distanceParameter Then
sh2.Rows(i).Copy _
sh3.Rows(i)
End If
sh3.Columns("A").insert
End Sub
OR
Sub Sample()
Dim sh2 As Worksheet, sh3 As Worksheet
Set sh2 = Worksheets("Sheet1")
Set sh3 = Worksheets("Sheet2")
sh2.Columns("A").insert
If distanceValue <= distanceParameter Then
sh2.Rows(i).Copy _
sh3.Rows(i)
End If
'The next line is to return the source data back to the original format remove if not needed
sh2.Columns("A").Delete
End Sub
Your last option and most dynamic would be to work with a listobject/DataTable instead of an excel range. IF POSSIBLE.
If you have a Table already Then you could simply use :
Sub Sample()
Dim sh2 As Worksheet, sh3 As Worksheet
Dim rngCurrentRow As Range
Set sh2 = Worksheets("Sheet1")
Set sh3 = Worksheets("Sheet2")
Set rngCurrentRow = sh2.ListObjects("YourTableNameHere").ListRows(i).Range
If distanceValue <= distanceParameter Then
rngCurrentRow.Copy _
sh3.Cells(i, 2)
End If
End Sub
Making a Range into a table is Very Easy, If your data does not contain blanks its as easy as clicking on the first cell in your Range and Pressing Ctrl+L
This will then select your range, If you need to increase the size of your range because it does contain spaces then simple change the input box to select all your Data.
Don't forget if you have heade3rs to check the check box
NOTE: If you are unsure of your Table name simply click on the table then on the ribbon a new tab will pop up and the end called Table Tools/Design. On that tab the left most area contains your table name, You can change this to anything you'd like.