Friday, July 31, 2009

How do I write this relative reference to columns in VBA (excel)?

I have Range("B1").Select, which is an integer (1-50), and I want to select the column which has the same number in the header row (row 1) that is the value of B1.





B1's value will change incrementally 1 to 50, and each time I invoke this macro I want it to select the next column and copy it.





This is what I want, but I don't know how to make it not always be "C:C". It should be "D:D" the next time, and so on.





Range("B1").Select


Columns("C:C").Select


Selection.Copy

How do I write this relative reference to columns in VBA (excel)?
Here's a function that will do it





Sub f()


   Range("B2").Select


   N = Selection.Value





   If (N %26lt;= 26) Then


      newCol = Chr(64 + N)


   Else


      newCol = Chr(64 + (N \ 26)) %26amp; Chr(64 + (N Mod 26))


   End If





   Columns(newCol %26amp; ":" %26amp; newCol).Select


End Sub





The value that you typed into cell B2 is used to create a character code for the column you want to highlight The ASCII code for A is 1+64, for B 2+64, etc





If you type in a number greater than 26 (for Z), then a two-letter code for the column is derived in the Else part of the If statement

baby breath

No comments:

Post a Comment