Forum Discussion

Paul_Fernando's avatar
Paul_Fernando
Copper Contributor
Nov 06, 2023

Unusual behaviour in excel

Sub LearnRange()

      Dim rng As range

      Set rng = range("a7:c7")

      rng.Select

      rng.Cells(7, 1).Select

End Sub

I created a new workbook with no other subroutines or control with no values in cells. The simple code above should execute and stop at selecting Cell(7,1) but it stops at selecting Cell(13,1). Why? 

3 Replies

  • JoeUser2004's avatar
    JoeUser2004
    Bronze Contributor

    Paul_Fernando  wrote:  ``selecting Cell(13,1). Why?``

     

    Because rng.Cells(7, 1).Select selects the 7th row, 1st column relative to the upper-left of the range defined for rng, namely A7:C7.

     

    Be that as it may, why are you doing rng.Select followed by a different Select, in the first place?

     

    If this is part of a recorded macro, note that Excel does a lot of superfluous Selects in recorded macros.

     

    It would behoove you to clean up that mess.

    • Paul_Fernando's avatar
      Paul_Fernando
      Copper Contributor

      JoeUser2004 

      It was meant to teach me the difference between a range select and a cells select. As it was indicated in the sub name it was meant merely to teach me different select commands. While thanking you for your response it gives no explanation as to why the selection jumps to the 13th row when I gave the code to select the 7th row !

      • JoeUser2004's avatar
        JoeUser2004
        Bronze Contributor

        Paul_Fernando  wrote:  ``While thanking you for your response it gives no explanation as to why the selection jumps to the 13th row when I gave the code to select the 7th row``

         

        Arguably, I was too presumptuous about your ability to interpret the English description.

         

        I wrote:  ``rng.Cells(7, 1).Select selects the 7th row, 1st column relative to the upper-left of the range defined for rng, namely A7:C7``.

         

        "Relative to" means "add 7" (minus 1).  "Upper-left of the range" refers to A7.

         

        So rng.Cells(7, 1).Address is A13 because the row number is 7 (from A7) plus 7 (from Cells(7,1)) minus 1.

         

        Also, the column number is 1 (for A) plus 1 (from Cells(7,1)) minus 1.

         

        I hope "minus 1" is obviously.  It is simply how we count the "n-th" ordinal position.