首页 > 解决方案 > 如何将一个单元格的值限制为另一个单元格的值?

问题描述

我有一张满是数字的桌子。我需要一个宏脚本,它将目标值与得分值进行比较。如果分值高于目标值,则将目标值更改为分值。

有人可以帮助我吗?

https://imgur.com/a/xmej0fi

我试图在一个单元格上应用以下代码,但它不起作用。

Sub check_value()
  If Cells(8, 23).Value < Cells(8, 24).Value Then
    Cells(8, 23).Value = Cells(8, 24).Value
  End If
End Sub

标签: excelvbacompare

解决方案


我认为这可能会对您有所帮助:

Option Explicit

Sub test()

    Dim LastRow As Long, Row As Long, Target As Long, Score As Long, LastColumn As Long, Column As Long

    With ThisWorkbook.Worksheets("Sheet1")

        LastColumn = .Cells(1, .Columns.Count).End(xlToLeft).Column
        LastRow = .Cells(.Rows.Count, 1).End(xlUp).Row

        For Column = 2 To LastColumn

            For Row = 2 To LastRow Step 2

                Target = .Cells(Row, Column).Value
                Score = .Cells(Row + 1, Column).Value

                If Score > Target Then
                    .Cells(Row, Column).Value = Score
                End If

            Next Row

        Next Column

    End With

End Sub

推荐阅读