View Single Post
  #2   Report Post  
Posted to microsoft.public.excel.programming
GS[_5_] GS[_5_] is offline
external usenet poster
 
Posts: 226
Default first sip of working with range in vba excel

bpascal123 explained :
Hi,

I have started learning vba for excel. Now, I feel fine with cells
workarounds in a loop or else. But when it comes to a range, I can't
find the reason why if I'm following the excel object model it's not
working.

Sub tryingtocopyrange()

Dim wkb1 As Workbook 'copy from wkb1
Dim wkb2 As Workbook 'copy to wkb2
Dim wks1 As Worksheet 'source sheet for wkb1
Dim wks2 As Worksheet 'destination sheet for wkb2

Set wkb1 = Workbooks("source.xls")
Set wkb2 = Workbooks("desti.xls")
Set wks1 = wkb1.Worksheets("mysource")
Set wks2 = wkb2.Worksheets("mydesti")

'A - the following is not working
'wks2.Range(Cells(1, 1), Cells(10, 3)) = wks1.Range(Cells(1, 1),
Cells(10, 3)).Value

'B - this is working but i'd rather use the cell method as i find it
easier to play with variables for indices in a loop
'wks2.Range("A1:C10") = wks1.Range("A1:C10").Value

'C - using the copy method, I should be able to copy a range and set
one cell as a destination
wks1.Range(Cells(1, 2), Cells(10, 2)).Copy
Destination:=wks2.Cells(4, 1)

End Sub

This little step that makes my life hard as a non-programmer trying to
code in vba, once over would take me to bigger steps such as copying
range into vba arrays...

Thanks,
Pascal


Pascal,
What you need to understand is the concept of 'fully qualified'
references. Consider this approach:

Sub CopyRange()
Dim wksSource As Worksheet, wksTarget As Worksheet

Set wksSource = Workbooks("source.xls").Sheets("mysource")
Set wksTarget = Workbooks("desti.xls").Sheets("mydesti")

With wksSource
.Range(.Cells(1, 2), .Cells(10, 2)).Copy _
Destination:=wksTarget.Cells(4, 1)
End With

'OR
wksTarget.Cells(4, 1) = _
wksSource.Range(wksSource.Cells(1, 2), wksSource.Cells(10, 2))
End Sub

--
Garry

Free usenet access at http://www.eternal-september.org
ClassicVB Users Regroup! comp.lang.basic.visual.misc