1

My table contains variable number of rows and three columns (A:C) that I am interested in

    A   B   C  D
1  xx  xx  xx  xxx
2  ....
3  ....
4  ...

I need to copy from WorkSheet1 to WorkSheet2

ws2.Range("A1").Value = ws1.Range("A1:C4").Value

The problem is that I do not want to hardcode C4 , because it can be C5 or C20 . How can I account for possible variable number of rows.


PS : I cannot use Range("A1").CurrentRegion because this will select more columns than needed, i.e. column D values will also get selected. Although it will select the correct number of rows

3
  • 1
    Will any rows below the chosen last row contain data? Commented Apr 26, 2014 at 2:36
  • Is your table a ListObject? If so, this is super easy. If not, you need some VBA to determine where the table "ends", which can be a little more difficult depending on the layout of your worksheet. Commented Apr 26, 2014 at 2:50
  • You might not have stumbled on THIS so give it a try? Commented Apr 26, 2014 at 3:30

3 Answers 3

4

There is more than one solution to most problems, but since CurrentRegion method returns the right number of rows (but the wrong number of columns), you could do something like this assuming you always need THREE columns.

Dim rng as Range
Set rng = ws1.Range("A1").CurrentRegion.Resize(,3)

ws2.Range(rng.Address).Value = rng.Value
Sign up to request clarification or add additional context in comments.

1 Comment

once you start using Resize and Offset your world will never be the same :)
2

I'm making an assumption that the last row in D will be equal to or less than the last row of A:C. I'm also assuming that the last row is determined by the last row that contains data.

Sub CopyColumnAtoC()
    Dim lastRow As Long

    lastRow = Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row

    ThisWorkbook.Worksheets(1).Range("A1:C" & lastRow).Copy

    ThisWorkbook.Worksheets(2).Range("A1:C" & lastRow).PasteSpecial xlPasteValues
End Sub

2 Comments

Typo (A2:C...) should be A1. Also, you can avoid actively using the .Copy method to copy/paste values, per OP's method of assigning the range's .Value. Cheers!
@David Thanks for pointing out the typo. I explicitly used the copy and paste as a safe guard in case my assumption about column D being longer were wrong. If Column D is longer, then the corresponding rows of A:C could possibly contain #N/A
1

You can specify just columns in a range. So

Sheet2.Range(Sheet1.Range("A:C").Address).Value = Sheet1.Range("A:C").Value

will copy columns A through C regardless of the rows in each column, i.e. if Column A has 8 rows, B has 6, and C has 11 it will still work.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.