当用户将鼠标悬停在单元格上时显示数据验证标准

问题描述 投票:0回答:2

我有以下Excel表格:

      A                   B                C    
1     Products            Price        Minimum Price
2     Product A           $30             $10  
3     Product B           $20             $25
4     Product C           $10             $15

用户应在B列中按每个产品定价。价格根据C列中的值进行限制。在数据验证菜单中,我使用了“十进制”标准,并将> = C2应用于B列中的每个值。限制工作正常。但是,稍后用户将看不到列C因此我还想要包含一个小窗口,当用户将鼠标悬停在列B中的单元格上时,该窗口显示列C中的值作为建议。

你们有没有想过如果可以使用Excel中的数据验证菜单,或者是否有可以执行此操作的宏?

谢谢你的帮助。

excel excel-vba vba
2个回答
2
投票

据我所知,你有两个选项可以在一个小窗口中显示一个值:

(1)你使用@Robin建议的Worksheet_ChangeWorksheet_SelectionChange事件。然而,这个解决方案有几种不同的“子选项”:

  1. 您可以使用其他答案中提出的comments
  2. 你可以创建一个小的自定义UserForm来显示你想要显示的任何信息。这种变化的好处在于,您可以根据自己的喜好自定义表单,并显示您想要的任何内容。以下显示了可以通过这种方式实现的一小部分样本。请注意,表单会自动显示,消失并使用光标调整其位置。

enter image description here

(2)你可以在你的帖子中使用最初要求的Data Validation。数据验证不仅允许您限制您希望允许的值。但您也可以指定输入消息并自定义错误消息(如果输入的值不正确)。下图为您提供了此解决方案的直观概念。

enter image description here

以下代码段可以帮助您自动设置所有产品的所有价格验证公式。

Option Explicit

Sub AutomaticallySetDataValidations()

Dim lngRow As Long
Dim strProduct As String
Dim dblMinimumPrice As Double

With ThisWorkbook.Worksheets(1)
    For lngRow = 2 To .Cells(.Rows.Count, "A").End(xlUp).Row
        strProduct = .Cells(lngRow, 1).Value2
        dblMinimumPrice = IIf(IsNumeric(.Cells(lngRow, 3).Value2), CDbl(.Cells(lngRow, 3).Value2), 0)
        If dblMinimumPrice > 0 Then
            With .Cells(lngRow, "B").Validation
                .Delete
                .Add Type:=xlValidateDecimal, AlertStyle:=xlValidAlertStop, Operator _
                    :=xlGreaterEqual, Formula1:=dblMinimumPrice
                .IgnoreBlank = True
                .InCellDropdown = True
                .InputTitle = "Price - " & strProduct
                .ErrorTitle = "Invalid price!"
                .InputMessage = "Please enter a new price for " & strProduct & _
                    ". The minimum admissable price for this product is " & Format(dblMinimumPrice, "$#,##0") & "."
                .ErrorMessage = "The price you entered is not acceptable. Please enter a new value."
                .ShowInput = True
                .ShowError = True
            End With
        Else
            Debug.Print "No data validation set for row " & lngRow & " since there is no valid minimum price."
        End If
    Next lngRow
End With

End Sub

2
投票

据我所知,数据验证菜单中没有选项。

但是,当Price列中的值更改时,您可以使用AddCommentRange方法来完成此操作。您可以使用Worksheet_Change事件来处理更改,然后应用注释:

Private Sub Worksheet_Change(ByVal Target As Range)

    Dim strMininmumPrice As String

    'test if change was made in price values
    If Not (Intersect(Target, Sheet3.Range("B2:B4")) Is Nothing) Then
        'add neighbour cell value to message
        strMinimumPrice = "Minimum price was: " & CStr(Target.Offset(0, 1).Value)

        'create and add comment to target cell
        Target.AddComment strMinimumPrice

    End If

End Sub

效果看起来像这样:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.