selecting a range within a range

前端 未结 2 1191
清酒与你
清酒与你 2021-01-03 05:38

I am using following VBA code (MS Excel 2010) to select a range of cells within a given range, to copy and insert the copied cells back into the source range: The range sta

相关标签:
2条回答
  • 2021-01-03 06:03

    I encountered the same behavior when getting an Excel range within a range in VB.Net. Tim's answer solved the weird behavior. At first I though it had something to do with the use of With but I guess it had something to do with the double relative referencing of dot notation as Tim had suggested.

    Public Sub SomeMergingFunction(ByRef inputRange As Excel.Range)
        With inputRange
            Debug.Print(.Address) ' $A$4:$A$130 correct
            Debug.Print(.Cells(1, 1).Address) ' $A$4 correct
            Debug.Print(.Range(.Cells(1, 1), .Cells(1, 1)).Address) ' $A$7 wrong
            Debug.Print(.Parent.Range(.Cells(1, 1), .Cells(1, 1)).Address) ' $A$4 correct
        End With
    End Sub
    
    0 讨论(0)
  • 2021-01-03 06:18

    Can confirm this behavior:

    Sub Tester()
    
        Dim rng As Range
    
        Set rng = Range("C3:H28")
    
        'This selects E5:F6 (???)
        With rng
            .Range(.Cells(1, 1), .Cells(2, 2)).Select
        End With
    
    
        'This selects C3:D4 (expected)
        With rng
            rng.Parent.Range(.Cells(1, 1), .Cells(2, 2)).Select
        End With
    
    End Sub
    

    Seems like it may be related to the "double relative" combination of using both .Range and .Cells

    Instead using rng.Parent.Range and having only the .Cells be relative to the containing range seems to fix it (and still allows for fully-qualified range references)

    0 讨论(0)
提交回复
热议问题