excel 在正确提供结果的列旁边填充其他值

wkyowqbh  于 2023-08-08  发布在  其他
关注(0)|答案(1)|浏览(88)

下面的代码按预期工作,使用A、B和C列中的3个标准获得最低速率,并从D列中找到最低值。结果添加到E列的每一行中。但由于某种原因,我得到了重复和错误的结果添加到F列,我不知道为什么?

Sub FindLowestValuewith3criteria()

Dim lastRow As Long
Dim ws As Worksheet
Dim dict As Object
Dim rng As Range
Dim cell As Range
Dim key As String
Dim minValue As Double

Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual

Set ws = ThisWorkbook.Sheets("Orbit") ' Replace "Sheet1" with the actual sheet name
lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
Set rng = ws.Range("A2:D" & lastRow) ' Assuming headers are in row 1
rng.Value = ws.Range("A2:D" & lastRow).Value

Set dict = CreateObject("Scripting.Dictionary")

For Each cell In rng
    key = cell.Value & "_" & cell.OffSet(0, 1).Value & "_" & cell.OffSet(0, 2).Value ' Combine three criteria values as the dictionary key
    
    If Not dict.exists(key) Then ' Check if the key already exists in the dictionary
        dict.Add key, cell(1, 4) ' If not, add the value from Column D as the initial value
    Else
        minValue = dict(key) ' Get the current minimum value for the key
        If cell(1, 4) < minValue Then ' Compare the current value with the minimum value
            dict(key) = cell(1, 4) ' Update the minimum value if the current value is lower
        End If
    End If
Next cell

' Output the minimum values in Column E
ws.Range("E2:E" & lastRow).ClearContents ' Clear previous results
For Each cell In rng
    key = cell(1, 1) & "_" & cell(1, 2) & "_" & cell(1, 3)
    cell(1, 5) = dict(key) ' Output the minimum value in Column E
Next cell

Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic

End Sub

字符串

cyvaqqii

cyvaqqii1#

您可以在一个数组中完成所有这些操作(而且速度会更快)

Sub FindLowestValuewith3criteria()

    Dim r As Long, ws As Worksheet, rng As Range
    Dim dict As Object
    Dim key As String, arr, v
    
    Set ws = ThisWorkbook.Sheets("Orbit") ' Replace "Sheet1" with the actual sheet name
    
    Set rng = ws.Range("A2:E" & ws.Cells(ws.Rows.Count, "A").End(xlUp).row)
    arr = rng.Value 'read all values into a 2D array, including col E
    
    Set dict = CreateObject("Scripting.Dictionary")
    For r = 1 To UBound(arr, 1)
        key = Join(Array(arr(r, 1), arr(r, 2), arr(r, 3)), "_")
        v = arr(r, 4)
        If Not dict.exists(key) Then
            dict.Add key, v
        Else
            If v < dict(key) Then dict(key) = v
        End If
    Next r
    
    For r = 1 To UBound(arr, 1)
        key = Join(Array(arr(r, 1), arr(r, 2), arr(r, 3)), "_")
        arr(r, 5) = dict(key)
    Next r
    
    rng.Value = arr  'put the array back on the sheet
    
End Sub

字符串

相关问题