0

I need to count the number of columns within a variable range and use the address of the last column to form part of defined range. Once I have defined the range I will want to input a formula. Can anyone please help?

Example

Dim lastcolumn as string

Lastcolumn = sheet("test").range("a1").end(xltoright).column

Sheets("test").range("b1:" & lastcolumn).select

Selection.formula = "myformula"
1
  • something like sheet("test").range("a1").end(xltoright).formula="xyz" should do it I think, last column would be an integer. or maybe cells(sheet("test").range("a1").end(xltoRight),1).formula Commented Sep 30, 2016 at 14:00

2 Answers 2

4

The column returns a number not a cell so you need to provide more info. You will need to use Cells().

Also avoid using Select it slows down the code:

Dim lastcolumn as Long

Lastcolumn = sheets("test").range("a1").end(xltoright).column

Sheets("test").range("b1",Sheets("test").Cells(1,lastcolumn)).formula ="myformula"
Sign up to request clarification or add additional context in comments.

6 Comments

Beat me to it - Nice answer! - I'd just maybe change lastcolumn to an integer.
Why not declare and treat lastcolumn as the integer that it is? (btw, it is Sheets, not Sheet).
@Jeeped got tied up in the other part missed that it was a string not a Integer/Long.
@Jeeped that's what i get by trying to be like you and just correct the code directly in the answer space and not through VBE.
LOL - Almost every time I try to correct code without the VBE I get bitten in the a$$! You are not following my posts' edit history of corrections! (btw, big day tomorrow... fingers crossed)
|
0

you can get rid of lastColumn calculation (and bothering about its type...)

With Sheets("test")
    .Range("B1", .Range("A1").End(xlToRight)).Formula = "myformula"
End With

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.