【问题标题】:Comparing cells to cells, when all the cells in the same column is equal, delete the whole column将单元格与单元格比较,当同一列中的所有单元格相等时,删除整列
【发布时间】:2021-01-25 13:04:05
【问题描述】:

我很难将我的逻辑放入 excel vba 代码中。 我的逻辑:将单元格与单元格进行比较,如果单元格 A > 单元格 B 则继续循环到下一列。当同一列的所有单元格具有相同的值时,删除整列。

Sub deletecol()
    Dim LastCol As Range, LastRow As Range, rRange As Range
    Dim i As Integer, j As Integer

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

    With ActiveSheet

        For i = 1 To LastRow
            For j = 1 To LastCol
                If ActiveSheet.Cells(1, 1).Value = ActiveSheet.Cells(i, 1).Value Then
                    Column(j).EntireColumn.Delete
                Else
                    ActiveSheet.Cells(1,1).Value > ActiveSheet.Cells(i,j).Value Then [this is the part that I'm stuck]
                
            Next j
        Next i

    End With
End Sub

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    我相信您目前所做的只是比较单元格对象。如果您想要这些值,则必须专门询问该值。

    ActiveSheet.Cells(1,1).Value > ActiveSheet.Cells(i, j).Value

    至于使用上述作为另一个条件,您可能需要查看 Elseif 关键字。

    考虑下面的代码

    If Range("a2").Value > 0 Then
        Range("b2").Value = "Positive"
    ElseIf Range("a2").Value < 0 Then
        Range("b2").Value = "Negative"
    End If
    

    这个页面在解释 VBA 中的条件控制方面做得相当不错 https://www.automateexcel.com/vba/else-if-statement

    【讨论】:

    • 好的,你知道 Else 部分该怎么做吗?
    • 我编辑了答案。希望这应该回答这个问题:)
    猜你喜欢
    • 2022-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-06
    • 2013-06-20
    • 2022-11-15
    • 1970-01-01
    相关资源
    最近更新 更多