[英]Type Mismatch in Excel Vba using Vlookup() Formula
I am new to VBA. 我是VBA的新手。 I wrote the following macro that gives me a 'type-mismatch' error (run-time error: 13). 我编写了以下宏,该宏给我一个“类型不匹配”错误(运行时错误: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. 最终,我的目的是将下拉列表与vlookup一起使用,以便选择下拉值会更改同一行其他列中的多个关联值。 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. 我猜想可能是我使用vlookup更改了值,这是我单击命令按钮时发生的固定的一次性事件。 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. 我需要提交一份包含9张纸的作品,每张纸都要做,因此要提交VBA。 Seems like some quick help is needed. 似乎需要一些快速帮助。 Thanks in advance! 提前致谢!
VLOOKUP()
has 3 important parameters, which should be passed. VLOOKUP()
具有3个重要的参数,应将其传递。 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. 在您的情况下,您要传递两个参数作为Range()
,这是VBA中的一个对象,并且需要该对象的Address
属性。
Long story short, change the .Formula
line to this: 长话短说,将.Formula
行更改为此:
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: 当公式正常运行时,这是Excel中.Formula
用法的一个很好的例子:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.