0

I am trying to insert a formula into a cell with a help of VBA and all of the time I receive error 1004: "Application-defined or object-defined error". Where does the problem lie?

Worksheets("Sheet1").Range("L10").Formula = "=VLOOKUP(" & Cells(6, 15) & ", SQLTable, 2, 0)*" & Cells(6, 16)
6
  • First Debug.Print "=VLOOKUP(" & Cells(6, 15) & ", SQLTable, 2, 0)*" & Cells(6, 16) and see how the result differs to the formula you would just write manually in the cell. Commented May 27, 2020 at 20:17
  • 1
    You may also want to qualify your Cells object (both instances) with a worksheet. Sheets("Sheet1").Cells(6, 15) etc.... or even better, create a worksheet variable for better readability Commented May 27, 2020 at 20:19
  • @BigBen I tried Debug.Print "=VLOOKUP(" & Cells(6, 15) & ", SQLTable, 2, 0)*" & Cells(6, 16) and got what actually was expected =VLOOKUP(06.01.2020, SQLTable, 2, 0)*-1000. This is exactly what it would look like, if I write it manually. Commented May 27, 2020 at 20:28
  • I'm not sure that's right... that 06.01.2020 would not work in a formula like that. Commented May 27, 2020 at 20:28
  • Write Worksheets("Sheet1").Select before your code line Commented May 27, 2020 at 21:12

1 Answer 1

2

I believe you want the address of Cells(6, 15) since you are dropping the formula on the sheet. Also amended to include a worksheet variable for proper object qualification


Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets("Sheet1")
ws.Range("L10").Formula = "=VLOOKUP(" & ws.Cells(6, 15).Address & ", SQLTable, 2, 0)"

This will default to the absolute address ($O$6). If you want to remove the columns being locked you can ammend the absolute properties (Column Absolute, Row Absolute) like so: ws.Cells(6, 15).Address (False, False)

Sign up to request clarification or add additional context in comments.

7 Comments

Thanks! Works perfectly! So the problem was that vba used the value in the cell and not the address as it would be correct for such formula?
Correct. You just need to tack on the multiplication part at the end using the same method (access the address that stores the value instead of the value)
... and of course, you can do "=VLOOKUP(O6, SQLTable, 2, 0)"
Sure! Thank you again :) Spent much more time than was needed for such a task :/
Yea, if you are using a static range then you may want to consider @BigBens comment. No point in beating around the bush with references when you could directly state the address. The current method would make more sense if you plan to sub out those row/column indexes with variables
|

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.