【问题标题】:VBA Macro Loop Through Columns in Rows and Compare ValuesVBA宏循环遍历行中的列并比较值
【发布时间】:2020-06-29 11:44:28
【问题描述】:

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

稍后,宏将根据结果更改其他单元格中的值。

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

我的代码是:

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

任何朝着正确方向轻推将不胜感激。我很想从谷歌那里得到答案,但我不能以一种对搜索引擎有意义的方式来表述这个问题:-)

再次感谢您的帮助!

【问题讨论】:

  • 可以肯定地说,每一列最后一行是不同的吗?因此,您正在遍历每一列,找到该列中的最后一个单元格并将其与上面的单元格进行比较?
  • 它大约有 300 行,对于某些列,您会在行方面有间隙,所以不幸的是不会那样工作。示例是:第 1 行在 10 列中有 10 个不同的值,第 2 行在 20 列中有 20 个值,第 3 行在 15 列中有 15 个值第 4 行在 30 列中有 30 个值等。所以如果我扫描第 16 列,那么它将停止立即因为第 1 行的值为空。同时行数在变化,所以现在是 300,第二天可能是 400 或更多。
  • 啊,是的,我最初读过,然后不知何故,我的思绪转到最后一行而不是最后一列。例如:在第 1 行中,最后一列是“M”,但可能是最后一列列是“H”?

标签: excel vba


【解决方案1】:

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

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

【讨论】:

  • 正是我想要的!我的主要问题是将值分配给变量并找到倒数第二列的值,只是不想为我工作。谢谢一百万!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-06-21
  • 2017-10-19
  • 1970-01-01
  • 2021-12-17
  • 1970-01-01
  • 2014-01-23
  • 1970-01-01
相关资源
最近更新 更多