首页 > 解决方案 > 如何从选择中定位特定范围的单元格?

问题描述

我想要的是能够选择任意数量的单元格并按下将注册信息的按钮。所有信息都是水平放置的,这意味着如果我选择 L10 并按下按钮,N10、O10 和 P10 将根据我告诉他们的内容进行更改。

我已经成功地做到了这一点,但它有一个小问题。只要所选单元格的信息是唯一的,它就可以正常工作。但我希望能够使用 L 列,它的随机数可能经常与其他单元格中的相同。

If cel.Value = Range("g16") Then                             

       Range("ff16").Value = True
       Range("p16").Value = Now

          If Range("m16").Value <= 0 Then
             Range("o16").Value = Range("o16").Value & " | " & VarNUMCB

          Else
          End If



  Else
    If cel.Value = Range("e16") Then
       Range("ff16").Value = True
       Range("p16").Value = Now
             If Range("m16").Value <= 0 Then
                Range("o16").Value = Range("o16").Value & " | " & VarNUMCB
             Else
             End If
    Else


    End If
  End If

预期的:

L10 选中,L11 选中,L18 选中,L23 选中 -> 按钮被按下 -> 弹出框要求签名 -> N10,N11,N18,N23 被勾选,O10,O11,O18,O23 显示签名和 P10,P11 ,P18,P23 显示日期和时间。

发生:如果来自 L 的值恰好与任何其他随机 L 单元格相同,它会将更改应用于两者,我不想这样做。

标签: excelvba

解决方案


也许你正在寻找这样的东西:

Sub tgr()

    Dim rSelected As Range
    Dim rCell As Range
    Dim sSignature As String
    Dim dtTimeStamp As Date

    'Verify that the current selection is a range (and not a chart or something)
    If TypeName(Selection) <> "Range" Then
        MsgBox "Invalid selection. Exiting Macro.", , "Error"
        Exit Sub
    End If

    'Get the signature
    sSignature = InputBox("Provide Signature", "Signature")
    If Len(sSignature) = 0 Then Exit Sub    'Pressed cancel

    'Get the current date and time
    dtTimeStamp = Now

    'Only evaluate selected cells in column L, ignore other selected cells
    Set rSelected = Intersect(Selection.Parent.Columns("L"), Selection)
    If rSelected Is Nothing Then
        MsgBox "Must select cell(s) in column L. Exiting Macro.", , "Error"
        Exit Sub
    End If

    'Loop through each selected L cell
    For Each rCell In rSelected.Cells
        '"Tick" same row, column N
        rCell.Offset(, 2).Value = "Tick"

        'Signature in same row, column O
        rCell.Offset(, 3).Value = sSignature

        'Date and time in same row, column P
        rCell.Offset(, 4).Value = dtTimeStamp
    Next rCell

End Sub

推荐阅读