excel - VBA 宏循环遍历行中的列并比较值

标签 excel vba

预先感谢您花时间阅读本文并为我提供帮助。我正在处理的宏的一部分应该遍历行并比较该行最后两个单元格中的值(每行的列将不同,因此我不能只采用特定两列中的值进行比较)。

稍后宏将根据发现更改其他单元格中的值。

我遇到的困难是分配行中最后一个单元格和最后一个单元格之前的值。

我的代码是:

Sub compareValues()

Dim allInLastRow As Long
Dim allInLastCol As Long

Dim i As Integer
Dim x As Integer

Dim allInWs As Worksheet

Set allInWs = ThisWorkbook.Worksheets("All In")
allInLastRow = allInWs.Range("C" & Rows.Count).End(xlUp).Row

For i = 2 To allInLastRow 'scans through all the rows
    allInLastCol = allInWs.Cells(i, Columns.Count).End(xlToLeft).Column
    
    For x = 1 To allInLastCol 'scans through all the columns in each row
    
    'in here I need to have the condition that compares lastcell value to 2nd last cell value and this is the one I have a problem with
    
    Next x
Next i


End Sub

任何朝着正确方向的插入都将不胜感激。我很想从谷歌那里得到答案,但我无法真正以对搜索引擎有意义的方式提出问题:-)

再次感谢您的帮助!

最佳答案

我可以想到找到行中的最后一列,然后找到行中的倒数第二列。

Sub LstRw_Stuff()
    
    Dim Rws As Long, r As Range, fRng As Range, col1 As Long, col2 As Long
    Dim rng1 As Range, rng2 As Range
    
    Set r = Range("A1")
    Rws = Cells.Find(What:="*", After:=r, SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
    For x = 2 To Rws
        col1 = Cells(x, Columns.Count).End(xlToLeft).Column
        Set rng1 = Cells(x, col1)
        s = rng1.Value
        rng1.ClearContents
        col2 = Cells(x, Columns.Count).End(xlToLeft).Column
        Set rng2 = Cells(x, col2)
        rng1 = s
        
        'do whatever need to be done for comparing
        If rng1 > rng2 Then
            MsgBox "yep" & rng1.Value & ">" & rng2.Value
        Else
            MsgBox "Nope" & rng1.Value & "<" & rng2.Value
            
        End If
        
    Next x
End Sub

关于excel - VBA 宏循环遍历行中的列并比较值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62637378/

相关文章:

mysql - VB - 连接到本地 SQL 服务器并将数据从 Excel 加载到表中

vba - 当用户在 Excel 中向右滚动时移动形状(VBA)

vba - 将表格粘贴到打开的 Word 文档中的书签处

excel - 覆盖单元格excel VBA的重新格式化

Excel 宏循环将后续行中的列连接到上方行中的列中

vba - 使用自定义 UI 功能区部署启用宏的 Word 模板 (.dotm)

excel - 根据约束对单元格进行着色

python - 使用 Openpyxl 读取时索引超出范围

vba - Excel - 添加动画

excel - 如果命名范围 COUNTIF 中存在列中的任何单元格,则复制行