0

I am new to VBA. I wrote the following macro that gives me a 'type-mismatch' error (run-time error: 13).

Private Sub CommandButton2_Click()
Set myrange = Sheet1.Range("B4081:F4094")
Sheet1.Cells(1634, 13).Formula = "=VLOOKUP(" & Sheets("Sheet1").Cells(1694, 2) & myrange & ", 2, False)"
End Sub

Ultimately, my intention is to use a drop-down list along with a vlookup so that selecting the drop-down value changes the multiple associated values in other columns in the same row. This small macro is supposed to be a part of the bigger one. Earlier, I was using something like this:

Sheet1.Cells(i, 3).Value = Application.VLookup(Sheet1.Cells(i, 2), myrange, 2, False)

The problem with this was that it didn't show the associated values when I selected an option from the drop-down. I guessed that may be I am changing the value using vlookup, which is a fixed, one-time event that happens when I click the commandbutton. So, I replaced this with a formula, thinking that due to the formula, values will change as and when I select an entry from the drop-down.

I need to submit a work constituting 9 sheets, in each of which I have to do this, hence the VBA. Seems like some quick help is needed. Thanks in advance!

Vityata
  • 42,633
  • 8
  • 55
  • 100
Sachin
  • 9
  • 1

1 Answers1

1

VLOOKUP() has 3 important parameters, which should be passed. In your case, you are passing 2 of the parameters as Range(), which is an object in VBA, and you need the Address property of the object.

Long story short, change the .Formula line to this:

Sheet1.Cells(1634, 13).Formula = "=VLOOKUP(" & Sheet1.Cells(1694, 2).Address & _
                                        "," & myRange.Address & ", 2, False)"

Or if you need some minimal example:

Sub TestMe()

    Dim myRange As Range
    Set myRange = Range("D1:E10")
    Cells(1, 1).Formula = "=VLOOKUP(" & Cells(2, 2).Address & "," _
                                & myRange.Address & ", 2, False)"

End Sub

This is a good example of .Formula usage in Excel, when you are having the formula functioning correctly:

Vityata
  • 42,633
  • 8
  • 55
  • 100