简体   繁体   中英

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

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

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.

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 eg

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM