简体   繁体   中英

How to set a new range variable to one cell address

I have the code below that works (almost)

Sub Find_PhaseCode_Cell2()
    Dim rng As Range
    Dim newrng As Range
    Dim wb As Workbook
    Dim ws As Worksheet
    Set wb = ThisWorkbook
    Set ws = Sheets("Control budget ")
    With ws
        Set rng = Range("b57:b64")
        With rng
            For x = 57 To 64
                If Cells(x, 2).Value <> "" Then
                    Debug.Print Cells(x, 2).Address
                End If
            Next x
        End With
    End With
End Sub

where the debug.print statement is, I would like that to be variable newrng .

If I try to set that set newrng = Cells(x,2).address , I get an error:

object required

What am I doing wrong?

You don't need the .address . All you need is this: Set newrng = Cells(x, 2)

It's within a 'With' statement so you should be referencing the members by prefixing a '.'

Also don't forget to use direct referencing (ie wb.Worksheets)

The following should be an example for you...

Sub Find_PhaseCode_Cell2()
    Dim rng As Range
    Dim newrng As Range
    Dim wb As Workbook: Set wb = ThisWorkbook
    Dim ws As Worksheet: Set ws = wb.Sheets("Control budget ")

    With ws.Range("B57:B64")
        For x = 57 To 64
            If .Cells(x, 2).Value <> "" Then
                Set newrng = .Cells(x, 2)
                Debug.Print newrng.Address
            End If
        Next x
    End With
End Sub

So the fix was not to declare newrng as a range. I left it as a variant, and the code below works now.

Sub Find_PhaseCode_Cell2()
    Dim rng As Range
    Dim newrng
    Dim wb As Workbook
    Dim ws As Worksheet
    Set wb = ThisWorkbook
    Set ws = Sheets("Control budget ")
    With ws
        Set rng = Range("b57:b64")
        With rng
            For x = 57 To 64
                If Cells(x, 2).Value <> "" Then
                    Debug.Print Cells(x, 2).Address
                    newrng = Cells(x, 2).Address
                    MsgBox newrng
                End If
            Next x
        End With
    End With
End Sub

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