好吧,我创建了一个包含两个字段的用户窗体。 一个是用作文本值(如“客厅”,“厨房”,“浴室”)的下拉列表的组合框... 第二个是文本框。 在此文本框中,我要显示房间名称的房间代码
我创建了表单
我有一个“图书馆”工作表
我有一个“ 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
任何帮助表示赞赏
答案 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