我有两张 Sheet(Sheet1 和 Sheet2)。Sheet2 的相邻单元格中有标题列表,标题数字为 1 或 3。Sheet 1 的标题相同,A 至 D 列的值为“TRUE”或“FALSE”。我希望如果 A:D 行中的所有值都是“FALSE”,则 E 列应返回 0。如果任何单元格包含“TRUE”,则使用标题从 Sheet2 执行 vlookup,并返回 Sheet2 中列出的每个标题相邻的数字。我编写了一个代码,它运行正常,但是,它为 Sheet2 第一行中的所有行返回相同的数字。您能指出错误在哪里吗?附图显示了我得到的输出。理想情况下,最后一行应该返回 1 而不是 3。
Sub UpdateOutput()
Dim ws1 As Worksheet
Dim ws2 As Worksheet
Dim headersRange As Range
Dim dataRange As Range
Dim outputRange As Range
Dim headersCell As Range
Dim dataRow As Range
Dim lookupValue As String
Dim lookupResult As Variant
Dim lr As Long
Set ws1 = ThisWorkbook.Worksheets("QMform")
Set ws2 = ThisWorkbook.Worksheets("NameList")
Set headersRange = ws2.Range("A2:B5")
lr = Cells(Rows.Count, 1).End(xlUp).Row
For i = 2 To lr
Set dataRange = ws1.Range("A" & i & ":D" & i)
Set outputRange = ws1.Range("E" & i & ":E" & i)
For Each dataRow In dataRange.Rows
If Application.WorksheetFunction.CountIf(dataRow, "TRUE") = 0 Then
outputRange.Cells(dataRow.Row - dataRange.Row + 1).Value = 0
Else
For Each headersCell In headersRange
lookupValue = headersCell.Value
If Application.WorksheetFunction.CountIf(dataRow, "TRUE") > 0 Then
lookupResult = Application.Vlookup(lookupValue, headersRange.Offset(0, 1), 2, False)
If Not IsError(lookupResult) Then
outputRange.Cells(dataRow.Row - dataRange.Row + 1).Value = lookupResult
End If
End If
Next headersCell
End If
Next dataRow
Next i
End Sub