循环内的VBA Vlookup

时间:2015-01-25 15:58:16

标签: excel vba loops find vlookup

用户在输入框中输入用户名("输入用户名"),它出现在第4行以后的第一列中(在代码中指定为单元格(4 + k-1,1))。他输入的用户名数量对应于他在第一个输入框中指定的特定日期显示的活动用户数("此日期有多少活动用户?")。

现在,我希望下一列(单元格(4 + k-1,2))执行vlookup或类似的函数,该函数接受第一列(同一行)中的用户名,并在表中找到相应的值一个不同的工作表(相同的工作簿!)。问题在于,无论我尝试什么,我都找不到能够实现这一目标的代码。我最简单的尝试在代码中显示如下,并返回消息"运行时错误1004:应用程序定义的错误或对象定义的错误"。

Sub Makro4()
    Dim dates As Date
    dates = InputBox("Enter the date of activity in the format dd/mm/yyyy:.")  ' User chooses date

    Dim n As Integer
    Dim k As Integer

    n = InputBox("Number of users active on this date:.")

    For k = 1 To n + 1                                       'Inserts rows accoring to number of users active on specified date
        Rows(4).Insert Shift:=xlDown, _
              CopyOrigin:=xlFormatFromLeftOrAbove
    Next

    For k = 1 To n
        Cells(4 + k - 1, 1) = InputBox("Enter username")
        Cells(4 + k - 1, 2) = Application.WorksheetFunction.VLookup(ActiveWorkbook.Sheets("Users by date").Range(4 + k - 1, 1), ActiveWorkbook.Sheets("Userlist").Range("B:j"), 9, False)
    Next

    Range(Cells(4, 3), Cells(4 + n - 1, 3)) = dates ' blank row between each date

End Sub

2 个答案:

答案 0 :(得分:0)

我认为您的问题出现在Range函数的第一个VLOOKUP描述中。如果要使用行/列号,请使用Cells来描述范围。

为了避免自己进行大量的打字实验,这应该可以解决您的问题:

With ActiveWorkbook.Sheets("Users by date")
    For k = 1 To n
        Cells(4 + k - 1, 1) = InputBox("Enter username")
        Cells(4 + k - 1, 2) = Application.WorksheetFunction.VLookup(.Cells(4 + k - 1, 1), ActiveWorkbook.Sheets("Sheet3").Range("B:j"), 9, False)
    Next
End With

答案 1 :(得分:0)

试试这个(未经测试,但编译)

注意:

1)始终尝试使用工作表对象限定Range()Cells()的每次使用

2)如果删除WorkSheetFunction,那么你可以测试返回值以查看它是否是错误,而不是让vlookup在没有匹配时触发运行时错误

Sub Makro4()
    Dim dates As Date
    dates = InputBox("Enter the date of activity in the format dd/mm/yyyy:.")  ' User chooses date

    Dim n As Integer
    Dim k As Integer
    Dim usr, v
    Dim shtUBD As Worksheet, shtUsers As Worksheet

    Set shtUBD = ThisWorkbook.Sheets("Users by date")
    Set shtUsers = ThisWorkbook.Sheets("Userlist")

    n = InputBox("Number of users active on this date:.")

    For k = 1 To n + 1 'Inserts rows accoring to number of users active on specified date
        shtUBD.Rows(4).Insert Shift:=xlDown, _
              CopyOrigin:=xlFormatFromLeftOrAbove
    Next

    For k = 1 To n
        usr = InputBox("Enter username")
        'If you drop the "WorkSheetFunction" then you can test the
        '  return value using IsError(), else it will raise an
        '  error if there's no match found for the username...
        v = Application.VLookup(usr, shtUsers.Range("B:J"), 9, False)

        With shtUBD.Rows(4 + k - 1)
            .Cells(1).Value = usr
            .Cells(2).Value = IIf(IsError(v), "?User?", v)
        End With
    Next
    ' blank row between each date
    shtUBD.Range(shtUBD.Cells(4, 3), shtUBD.Cells(4 + n - 1, 3)) = dates

End Sub