VBA 循环内的 Vlookup

VBA Vlookup within loop

用户在输入框 ("Enter username") 中输入用户名,输入框出现在从第 4 行开始的第一列(在代码中指定为单元格 (4+k-1,1))。他输入的用户名数量对应于他表示在第一个输入框 ("How many users active on this date?") 中指定的特定日期处于活动状态的用户数量。

现在,我希望下一列 (cells(4+k-1,2)) 执行 vlookup 或类似函数,该函数采用第一列(同一行)中的用户名并在table 在不同的工作表中(相同的工作簿!)。问题是无论我尝试什么,我都找不到使它起作用的代码。我最简单的尝试是在代码中呈现如下,并且returns一条消息"run time error 1004: application-defined or object-defined error".

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

我认为您的问题出在 VLOOKUP 函数的第一个 Range 描述中。如果要使用 row/col 数字,则使用 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) 始终尝试使用工作表对象

限定每次使用 Range()Cells()

2) 如果删除 WorkSheetFunction 那么您可以测试 return 值以查看它是否是一个错误,而不是让 vlookup 触发 运行-time 错误,如果没有匹配项

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