将 VLookup 公式设置为 excel 单元格
Posted
技术标签:
【中文标题】将 VLookup 公式设置为 excel 单元格【英文标题】:Setting A VLookup formula to excel cells 【发布时间】:2014-04-14 18:38:52 【问题描述】:对不起,如果我搞砸了一些格式,但这是我的第一个问题。我正在尝试制作一个将单元格值设置为 VLookup 函数的 excel 宏。它接受来自 userForm 的输入以确定范围、Vlookup 的工作表、输出列和查找值。尝试使用此功能时出现大量错误。任何帮助将不胜感激!
Sub Go_Click()
Dim First As Boolean
Dim Start As Integer
First = True
Start = LookupName.Value
Sett Start, First
End Sub
Sub Sett(Start As Integer, First As Boolean)
'EXIT WHEN NO VALUE IS FOUND WHERE NAME IS SUPPOSED TO BE
If IsEmpty(Cells(Start, 1)) Then
If First = False Then
Exit Sub
End If
End If
Dim val As String
val = Cells(Start, 1).Value
Dim Hincrement As Integer
Hincrement = 1 'start at col 2 (increments in loop)
Dim sheetname1 As String
Dim start_range As String
Dim end_range As String
sheetname1 = name_of_sheet.Value
start_range = RangeStart.Value
end_range = RangeEnding.Value 'all values saving correctly
Dim myRange As Range
Dim ending As Integer
ending = (Start) + Range(start_range, end_range).Columns.Count
Cells(1, 17) = ending
Dim out As Integer
out = Output.Value
Dim ptr As Integer 'stays at original start point
For ptr = Start + 1 To ending
Hincrement = Hincrement + 1
Worksheets("Sheet1").Range(ptr, out).Formula = "=VLookup(val, Worksheets(sheetname1).Range(start_range, end_range), Hincrement, False)"
Next ptr
End Sub
【问题讨论】:
I get a multitude of errors
- 你能详细说明一下吗?也可以试试Worksheets("Sheet1").Range(ptr, out).Formula = "=VLookup(" & val & ",'" & sheetname1 & "'!" & Worksheets(sheetname1).Range(start_range, end_range).Address & "," & Hincrement & ", False)"
我收到运行时错误“'1004':应用程序定义或对象定义错误。”错误发生在 VLookup 语句中。还尝试了您提供的语法,但不幸收到相同的错误
尝试添加行 Debug.Print "=VLookup(" & Val & ",'" & sheetname1 & "'!" & Worksheets(sheetname1).Range(start_range, end_range).Address & "," & Hincrement & ", False)"
。它产生什么输出(按CTRL+G查看)?
=VLookup(Miles Matheson,'Sheet2'!$A$2:$E$7,2, False) 即是输出,也是正确的VLookup信息……
好的,试试Worksheets("Sheet1").Cells(ptr, out).Formula = "=VLookup(""" & val & """,'" & sheetname1 & "'!" & Worksheets(sheetname1).Range(start_range, end_range).Address & "," & Hincrement & ", False)"
【参考方案1】:
作为 cmets 的后续,这个可行:
Worksheets("Sheet1").Cells(ptr, out).Formula = "=VLookup(""" & val & """,'" & sheetname1 & "'!" & Worksheets(sheetname1).Range(start_range, end_range).Address & "," & Hincrement & ", False)"
【讨论】:
以上是关于将 VLookup 公式设置为 excel 单元格的主要内容,如果未能解决你的问题,请参考以下文章
Excel表提示“无效引用 ,公式中所引的单元格不能位于256列或65536行后”这个错误
EXCEL中如何在A1单元格输入数据, B2单元格以Code128条码显示A1的数据
Excel使用VLOOKUP函数填充后有的单元格会出现 #N/A 这个符号,是怎么回事?