Excel根据匹配的行和匹配的列输入表格

时间:2018-11-20 15:40:01

标签: excel vba excel-vba

基本上,我正在尝试创建“数据输入”标签。我有两个数据验证输入框,它们从表中动态提取数据。第一个单元格根据人员的姓氏进行索引(表2 [LAST])。第二个单元格索引Table1 [#HEADERS]。尽管这些都很好,但我需要在工作表单元格中将这两个单元格相交,然后将相交的单元格转换成数据输入表中单元格的数据。

工作表1上的单元格“ B2”是数据验证类型列表,具有从表2的下拉列表(最后一个)(在工作表2中)

工作表1上的单元格“ C2”是数据验证类型列表,并具有表1的下拉列表[#HEADERS](在工作表2中)

工作表1上的单元格“ D2”是数据验证类型“日期”,当我按下按钮时,它将被推到工作表2上相交的单元格中。下面的代码是我发现并粘在一起的东西,我无法弄清楚为什么它在最后一行失败。

Sub Button5_Click()

    Dim wsInfo As Worksheet: Set wsInfo = Worksheets("worksheet2")
    Dim lookupRange As Range
    Dim matchval As Range
    Dim indexVar As Long
    Dim myVal As Variant
    Dim matchval2 As Range
    Dim lookuprange2 As Range

    Set matchval = Sheets("worksheet1").Range("B2")
    Set lookupRange = wsInfo.Range("Table2[LAST]")
    If Not Application.WorksheetFunction.Sum(lookupRange) = 0 Then
        indexVar = Range(Application.Index(lookupRange, Application.Match(matchval, lookupRange))).Row
    End If

    Set matchval2 = Sheets("worksheet1").Range("B3")
    Set lookuprange2 = wsInfo.Range("Table1[#HEADERS]")
    If Not Application.WorksheetFunction.Sum(lookupRange) = 0 Then
        columnVar = Range(Application.Index(lookupRange, Application.Match(matchval2, lookuprange2))).Column
    End If

    wsInfo.Cells(indexVar, columnVar) = Sheets("worksheet1").Cells(2, "D").Value
End Sub

如果数据验证列表中有一个更简单的方法可以提供相对参考,我可以使用它。它还将说明重复的姓氏。

1 个答案:

答案 0 :(得分:1)

感谢SJR向我指出了正确的方向。

Sub Button5_Click()

    Dim wsInfo As Worksheet: Set wsInfo = Worksheets("worksheet2")
    Dim pltws As Worksheet: Set pltws = Worksheets("Data Entry Tab")
    Dim lookupRange As Range
    Dim myVal As Variant
    Dim lookuprange2 As Range

    'Set row value to look for
    matchval = pltws.Cells(2, "B").Value
    'Set column to look in
    Set lookupRange = wsInfo.Range("Table2[LAST]")
    'Set column value to look for
    matchval2 = pltws.Cells(2, "C").Value
    'Set row to look in
    Set lookuprange2 = wsInfo.Range("Table1[#HEADERS]")

    'Returns row (Relative to the actual range provided, not the worksheet) that data is found on
    indexVar = Application.Match(matchval, lookupRange, 0)
    'Returns column (Also relative to the range provided, not the worksheet) that the data is found in
    columnVar = Application.Match(matchval2, lookuprange2, 0)

    'Have to offset to account for actual tables position in the worksheet.
    wsInfo.Cells(indexVar + 3, columnVar + 3).Value = pltws.Cells(2, "D").Value

End Sub