VLOOKUP不返回结果

时间:2019-10-07 08:12:48

标签: excel vba vlookup

好吧,我创建了一个包含两个字段的用户窗体。 一个是用作文本值(如“客厅”,“厨房”,“浴室”)的下拉列表的组合框... 第二个是文本框。 在此文本框中,我要显示房间名称的房间代码

我创建了表单

  • 组合框称为RoomNames
  • 文本框称为RoomTypes

我有一个“图书馆”工作表

  • 第1列= RoomTypes(从1到n的整数值)
  • 第3列=房间名称(文本)

我有一个“ ROOMBOOK”

在这里我要添加选定的RoomType和RoomName

当我使用for循环并与if语句进行比较时,代码按预期运行,结果是每个RoomName的RoomTypes代码。 “ ROOMBOOK”的输出也可以按预期工作。

当我使用VLOOKUP时,我只会收到类型不匹配错误。 这里的代码

Private Sub InsertButton_Click()
'find last filled row
lastrow = ThisWorkbook.Worksheets("ROOMBOOK").Cells(Rows.Count, 2).End(xlUp).Row
' get text
ThisWorkbook.Worksheets("ROOMBOOK").Cells(lastrow + 1, 2).Value = RoomNames.Text

Me.RoomTypes = Application.WorksheetFunction.VLookup(RoomNames.Text, Worksheets("LIBRARY").Range("A5:C50"), 1, 0)

ThisWorkbook.Worksheets("ROOMBOOK").Cells(lastrow + 1, 1).Value = RoomTypes.Text
End Sub

VLookup语句导致运行时错误1004

任何帮助表示赞赏

1 个答案:

答案 0 :(得分:1)

按照您的说法,您似乎正在尝试并在不允许的“向后”模式下使用VLOOKUP(在第三列中找到一个匹配项,并在第一列中返回相应的值)

使用Match()函数获取找到的值的索引,然后将其用作Cells(rowIndex, colIndex)上下文中的rowIndex参数:

Me.RoomTypes.Text = ThisWorkbook.Worksheets("LIBRARY").Range("A5:A50").Cells(Application.WorksheetFunction.Match(Me.RoomNames.Text, ThisWorkbook.Worksheets("LIBRARY").Range("C5:C50"), 0), 1)

顺便说一句,您应该养成使用{em> explicit Range资格直到Workbook对象的习惯,其示例如下:

Option Explicit

Private Sub InsertButton_Click()
    Dim lastrow As Long

    With ThisWorkbook ' reference wanted workbook
        Me.RoomTypes.Text = .Worksheets("LIBRARY").Range("A5:A50").Cells(Application.WorksheetFunction.Match(Me.RoomNames.Text, .Worksheets("LIBRARY").Range("C5:C50"), 0), 1)

        With .Worksheets("ROOMBOOK") 'reference wanted worksheet of referenced workbook
            lastrow = .Cells(.Rows.Count, 2).End(xlUp).Row 'find last not empty cell row index in referenced worksheet column B
            .Cells(lastrow + 1, 1).Value = Me.RoomTypes.Text
            .Cells(lastrow + 1, 2).Value = RoomNames.Text
        End With
    End With
End Sub
相关问题