【问题标题】:Finding counter part records in an excel sheet在 Excel 工作表中查找对应零件记录
【发布时间】:2018-09-27 16:11:34
【问题描述】:

我只是想创建一个普通的宏来执行以下操作:

如果有对应记录,它只是检查不同的数据集。 首先,它检查是否找到相同的金额,如果是,则检查日期和文本。如果一切都相同,则应突出显示该记录。 我是新手,所以我在第一步尝试检查正确的数量并突出显示单元格,但即使这也不是真的有效:(。我只是用双循环尝试过,这里是代码:

Dim row1 As Integer
Dim row2 As Integer
Dim index1 As Integer
Dim index2 As Integer

index1 = 0
index2 = 0
row1 = 2
row2 = 10

Do
 Do
    If Cells(row1, 1).Value = Cells(row2, 13).Value Then
    Cells(row1, 1).Interior.ColorIndex = 3
        Exit Do
    End If
    row2 = row2 + 1
   index2 = index2 + 1
  Loop Until index2 = 12

    index1 = index1 + 1
    row1 = row1 + 1
Loop Until index1 = 5

稍后我还想包含一个计算行数的函数,这样如果行数发生变化,这个宏也可以工作。

Excel 宏扩展:

【问题讨论】:

  • 那么第 13 列是 M 列,你的意思是把它写成 Cell(row2, 13).Value

标签: vba excel duplicates


【解决方案1】:

因此,为了针对多个条件进行测试,您需要使用 And 并每次更改 Cells 语句中的列位置。

您还需要在第二个 Do 循环之后将 index2 重置为 0,否则它将超过 12 并且永远不会满足您的退出条件 Loop Until index2 = 12,从而导致 Overflow

要突出显示整行(而不仅仅是 A 列,您需要使用 Range(Cells(x, y), Cells(x, y)) 来指示该范围。

最后,您需要将第一个循环退出标准设为 Loop Until index1 = 4,因为由于您将 index1 初始化为 0,因此 5 次迭代相当于 0 到 4,而不是 0 到 5。

(另外,我不理会您的变量,但请注意,在声明 Loops 中使用的变量时,最佳做法是将它们声明为 Longs,而不是 Integers。整数最多约 32,000 行,其中Longs 可以超过一百万。)

Sub Test()
Dim row1 As Integer
Dim row2 As Integer
Dim index1 As Integer
Dim index2 As Integer

index1 = 0
index2 = 0
row1 = 2
row2 = 10

Do
    Do
        If Cells(row1, 1).Value = Cells(row2, 1).Value And _
           Cells(row1, 3).Value = Cells(row2, 3).Value Then
            If Cells(row1, 2).Value <> Cells(row2, 2).Value Then
                Range(Cells(row1, 1), Cells(row1, 3)).Interior.ColorIndex = 3
                Range(Cells(row1, 2), Cells(row1, 2)).Interior.ColorIndex = 6
                Range(Cells(row2, 1), Cells(row2, 3)).Interior.ColorIndex = 3
                Range(Cells(row2, 2), Cells(row2, 2)).Interior.ColorIndex = 6
            Else
                Range(Cells(row1, 1), Cells(row1, 3)).Interior.ColorIndex = 3
                Range(Cells(row2, 1), Cells(row2, 3)).Interior.ColorIndex = 3
                Exit Do
            End If
        End If

        row2 = row2 + 1
        index2 = index2 + 1

    Loop Until index2 = 12

    row1 = row1 + 1
    index1 = index1 + 1
    index2 = 0
    row2 = 10

Loop Until index1 = 4

End Sub

【讨论】:

  • 哇,感谢 dwirony 的出色回答!是否也可以逐步检查日期和文本?因此将首先检查该金额,如果金额与宏检查日期匹配,如果日期不匹配,则将其涂成黄色,然后检查文本,如果文本相同,则将其涂成红色,如果日期和文本不匹配什么都不会被着色(也不是数量)?如果这对您来说只是一件快速的事情,如果您能帮助我,那就太好了,否则我会自己尝试,但我认为我不能以有效的方式做到这一点;)
  • @Dupor 如果日期和文本都匹配怎么办?
  • 在这种情况下,金额日期文本将为红色。匹配的所有内容都是红色的,不匹配的将是黄色的,但如果金额不匹配,则不会着色。
  • @Dupor 我需要您提供的关于预期结果的更新图片。您在上面发布的图片不反映您现在正在编写的标准 - 我希望第二个 13 金额线是黄色的,因为它上面有一个匹配的金额线,没有匹配的日期。
  • @Dupor 请注意,我在代码中添加了另一行 (row2 = 10)。这缺少某些行的一些迭代。这将抓住一切。
猜你喜欢
  • 2013-08-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-23
  • 2011-01-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多