I'm trying to make a program in the Excel VBA that inserts a formula into a column of cells. This formula changes based on the contents of the cell directly to the left. This is the code I have written so far:
Sub Formula()
Dim colvar As Integer
colvar = 1
Dim Name As String
Name = "Sample, J."
Do While colvar <= 26
colvar = colvar + 1
Name = Range("B" & colvar).Value
Range("C" & colvar).Value = "='" & Name & "'!N18"
Loop
End Sub
As you can see, I want to insert the variable Name
between the formula strings, but Excel refuses to run the code, giving me a "application-defined or object-defined error."
Is there a way to fix this?
2条答案
按热度按时间thtygnil1#
You will need some error checking in case the sheets don't actually exist in the workbook.
it looks like you are looping through column B that has a list of sheet names and want range N18 to display next to it.
Something like
Or you can just list the sheets and show N18 next to it, run this code in a Sheet named "Sheet1"
gc0ot86w2#
Thank you to everyone for your help! I actually found that I had just made a silly error: the line
Do While colvar<=26
should have beenDo While colvar<26
. The cells were being filled, but the error manifested because one cell was being filled by a nonexistent object.I did decide to use the
.Formula
modifier rather than.Value
. Thank you to Jeeped for suggesting that.