Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create variable for cell location

Tags:

excel

vba

I need to create a variable for the start location of this cell copy/paste, so I can use it as a reference point for other data. Is that possible? I'm not sure of the syntax.

wbkCS.Worksheets("Cut Sheet").Range("S4:S2000").Copy

With wbkVer.Worksheets("Cutsheets")
   .Range("A" & .Rows.Count).End(xlUp).Offset(1).PasteSpecial xlPasteValues
End With
like image 347
Mike Avatar asked Apr 26 '26 22:04

Mike


2 Answers

Here's the syntax for saving those ranges as Range objects.

dim firstRange as Range, secondRange as Range

set firstRange = wbkCS.Worksheets("Cut Sheet").Range("S4:S2000")

firstRange.copy

With wbkVer.Worksheets("Cutsheets")
    set secondRange = .Range("A" & .Rows.Count).End(xlUp).Offset(1)
    secondRange.PasteSpecial xlPasteValues
End With

If you wanted the 1st cell for one of those ranges, it would be like this:

firstRange.Cells(1,1)

like image 123
Daniel Avatar answered Apr 28 '26 11:04

Daniel


You already have the answer but also what can be nice is to avoid the clipboard altogether with something like this:

Sub WithoutClipboard()

'define the two ranges variables
Dim firstRange As Range
Dim secondRange As Range

'set the range variables to specific ranges
Set firstRange = wbkCS.Worksheets("Cut Sheet").Range("S4:S2000")
With wbkVer.Worksheets("Cutsheets")
    Set secondRange = .Range("A" & .Rows.Count).End(xlUp).Offset(1)
End With

'resize the second range so it exactly the same size as the first range
With firstRange
      Set secondRange = secondRange.Resize(.Rows.Count, .Columns.Count)
End With

'move the data without having to use copy/paste
secondRange.Value = firstRange.Value

End Sub
like image 29
whytheq Avatar answered Apr 28 '26 12:04

whytheq