【问题标题】:Compare and select Excel Macro比较并选择 Excel 宏
【发布时间】:2017-03-21 00:26:11
【问题描述】:

我有 2 个 Excel 工作表。在一张纸上 (sh1) 我有 B 列的日期和 D:I 列的数字。

我想要一个宏,如果列范围 D:I 中的一个单元格包含值“2”,则单击该单元格获取属于该单元格行的日期值并进行比较我的另一张表 (sh2) 中的日期值。

第二张表中的日期值也在 B 列中。

到目前为止我所拥有的:

    Option Explicit

    Private Sub Worksheet_SelectionChange(ByVal Target As Range)

      Dim Date1 As Date
      Date1 = Range("B" & ActiveCell.Row).Value

      If Selection.Count = 1 Then
        If Selection.Value = 2 Then
          If Not Intersect(Target, Range("D:I")) Is Nothing Then
            MsgBox Date1
          End If
        End If
      End If

   End Sub

此代码已将变量分配给属于被单击单元格的行的日期。我被困在我将该变量与第二张表中的日期进行比较的部分。

最终,我想这样当它在第二张表中找到匹配项时,它会选择该行。

【问题讨论】:

    标签: vba excel vlookup


    【解决方案1】:

    您的代码已修改:

    Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    
        Dim Date1 As Date
    
        Date1 = Range("B" & ActiveCell.Row).Value
    
        If Selection.Count = 1 Then
            If Selection.Value = 2 Then
            If Not Intersect(Target, Range("D:I")) Is Nothing Then
                foundDate = Date1
                Call findDateOnSheet2
                End If
            End If
        End If
    End Sub
    

    和(可能的解决方案)您需要在 sheet2 上找到该行:

    Option Explicit
    Public foundDate As Date
    
    Sub findDateOnSheet2()
        Dim i As Long
        i = 1
        Do While Sheets(2).Cells(i, 2).Value <> ""
            If Sheets(2).Cells(i, 2).Value = foundDate Then
                Sheets(2).Activate
                Sheets(2).Rows(i).Select
                Exit Do
            End If
            i = i + 1
        Loop
    End Sub
    

    EDIT1:

    您的工作表可能与我的测试表不同。您应该根据工作表的结构修改我的代码中的起始值和/或其他参数

    我的第一张纸:

    第二个

    【讨论】:

    • 如果我错了,请纠正我。我制作了一个包含子 FindDateOnSheet2 的新模块(Module1)。使用 Application.Run "Module1.findDateOnSheet2" 从 Worksheet_SelectionChange 子调用它,但没有任何反应..
    • 你不需要Application.Run "Module1.findDateOnSheet2"。如果您使用我的 Worksheet_SelectionChange(...) 覆盖您的代码,并在您编写时使用我的findDateOnSheet2() 创建一个模块。然后,您只需单击第一张工作表上的一个单元格。如果您单击数字 2,它会自动选择找到所选日期的行。
    • 这对我不起作用。如果我对 foundDate 变量进行监视,它会说该变量的值超出范围。
    • 我编辑了我的答案并向你展示了我的床单......我希望它有所帮助
    • 非常感谢,一旦我开始摆弄 i 变量,我就想通了,我不得不将它设置为 3,因为我在实际数据上方有 2 个不相关的行。
    猜你喜欢
    • 1970-01-01
    • 2011-07-31
    • 2016-12-19
    • 2013-10-14
    • 2019-03-13
    • 2020-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多