有没有一种方法可以在基于另一列的另一列中输出值?

时间:2019-04-23 20:02:04

标签: excel vba

我试图通过将表中的一列基于其他两列的值来创建输出。

我尝试使用变量,并认为我已经开始使用循环了。我一直遇到的问题是“不匹配”和“全局”

Private Sub formatcolumnF()

Dim eqa As Range, eqt As Range

Set eqa = ActiveSheet.Range("D2", Range("D2").End(xlDown))
Set eqt = ActiveSheet.Range("C2", Range("C2").End(xlDown))

Dim result As String, Cell As Range

For Each Cell In eqa
     If Cell >= eqt.Value + 0.025 Then
            result = "OVER"
     ElseIf Cell <= eqt.Value - 0.025 Then
            result = "UNDER"
     ElseIf Cell <= eqt.Value + 0.025 Or Cell >= eqt.Value - 0.025 Then
            result = "ON TARGET"
     Else
            result = ""
     End If
Next Cell

Range("F2", Range("F2").End(xlDown)).Value = result

End Sub

我希望F列中的输出是字符串结果之一。当我为表中的特定行运行该代码时,该代码有效,但是当我尝试为整个列运行该代码时,则无效。

1 个答案:

答案 0 :(得分:0)

此作品有效:

Private Sub FormatcolumnF()

    Dim eqa As Range, eqt As Range

    Set eqa = ActiveSheet.Range("D2", Range("D2").End(xlDown))
    Set eqt = ActiveSheet.Range("C2", Range("C2").End(xlDown))

    Dim result As String, Cell As Range

    For Each Cell In eqa.Cells
        If IsNumeric(Cell) Then
            If Cell.Value >= Application.Sum(eqt.Value) + 0.025 Then
                Cells(Cell.Row, "F") = "OVER"
            ElseIf Cell <= Application.Sum(eqt.Value) - 0.025 Then
                Cells(Cell.Row, "F") = "UNDER"
            ElseIf Cell <= Application.Sum(eqt.Value) + 0.025 _
            Or Cell >= Application.Sum(eqt.Value) - 0.025 Then
                Cells(Cell.Row, "F") = "ON TARGET"
            End If
        End If
    Next Cell

End Sub

代码中的问题主要是eqt.Value不返回值,因为eqt范围是多个单元格。因此,应使用Application.Sum(eqt.Value)。此外,我在此处的循环中添加了一个额外的检查-单元格是否为数字-If IsNumeric(Cell) Then。最后,使用CElls(Cell.Row,“ F”),用OVER和UNDER更新行“ F”中的相应单元格。通过避免使用ActiveSheet并声明工作表,可以进一步改进代码。看一下RangeCells之前的点,它们引用了With中的工作表。

How to avoid using Select in Excel VBA

Option Explicit

Private Sub FormatcolumnF()

    Dim eqa As Range, eqt As Range
    Dim wks As Worksheet
    Set wks = ThisWorkbook.Worksheets(1) 
    'or even better by name like "Worksheets(Table1)"

    With wks
        Set eqa = .Range("D2", .Range("D2").End(xlDown))
        Set eqt = .Range("C2", .Range("C2").End(xlDown))
    End With

    Dim result As String, cell As Range

    With wks
        For Each cell In eqa.Cells
            If IsNumeric(cell) Then
                If cell.Value >= Application.Sum(eqt.Value) + 0.025 Then
                    .Cells(cell.Row, "F") = "OVER"
                ElseIf cell <= Application.Sum(eqt.Value) - 0.025 Then
                    .Cells(cell.Row, "F") = "UNDER"
                ElseIf cell <= Application.Sum(eqt.Value) + 0.025 _
                    Or cell >= Application.Sum(eqt.Value) - 0.025 Then
                    .Cells(cell.Row, "F")  = "ON TARGET"
                End If
            End If
        Next cell
    End With

End Sub