Spd
Spd

Reputation: 33

assign active cell address to range variable

I get Error 1004 "Application-defined or Object-defined error" on this line:

 `ws2.range(dstRef).offset(srn,0).value= srn+1`

Why is that?

Dim ws1, ws2 As Worksheet
Set ws1 = Worksheets("Tabelle1")
Set ws2 = Worksheets("Packinglist_Annexure-1")

Dim srcRef, dstRef, tempAdr As Range
Set dstRef = Range("C19")

Dim k, srn As Integer
k = reqRow
srn = 0
For k = reqRow To row1
    ws2.Activate
    ws2.Range(dstRef.Address).Offset(srn, 0).Value = srn + 1
    ws1.Activate
    ws1.Range(reqAddr.Address).Offset(0, srn).Copy Destination:=ws2.Range(dstRef.Address).Offset(1, srn)
    srn = srn + 1
Next k

Upvotes: 0

Views: 2322

Answers (3)

d219
d219

Reputation: 2834

The error is occurring as you are trying to set the string (that specifies the cells to be used) as a range rather than a string. You can declare dstRef as a string and use this on that line e.g.

Dim srcRef, tempAdr As Range
Dim dstRef As String
Dim srn As Integer

dstRef = "C19"
srn = 0
ws2.Activate

ws2.Range(dstRef).Offset(srn, 0).Value = srn + 1

Upvotes: 0

user4039065
user4039065

Reputation:

I believe you are looking for the range.address property although I'm unclear on why Range("C19") has no parent worksheet reference.

Dim ws1 As Worksheet, ws2 As Worksheet
Set ws1 = Worksheets("Tabelle1")
Set ws2 = Worksheets("Packinglist_Annexure-1")

Dim srcRef As Range, dstRef As Range, tempAdr As Range
Set dstRef = ws1.Range("C19")

Dim srn As Integer
srn = 0
ws2.Activate
ws2.Range(dstRef.ADDRESS).Offset(srn, 0).Value = srn + 1

Is the . in .Range necessary when defined by .Cells?

You need to declare all of the vartypes in a dim line.

dim a, b, c, d as string

The above only dimms d as a string; everything else is a variant.

Upvotes: 1

DisplayName
DisplayName

Reputation: 13386

you either use

ws2.Range(dstRef.Address).Offset(srn, 0).Value = srn + 1

or

ws2.Range("C19").Offset(srn, 0).Value = srn + 1

BTW you'd better explicily declare all your variables or they will be implicitly assume as of Variant type:

Dim ws1 , ws2 As Worksheet ' w1 is of Variant type and w2 is of Worksheet type

Dim ws1 As Worksheet, ws2 As Worksheet ' both w1 and w2 are of Worksheet type

Upvotes: 1

Related Questions