Type error on merged cells in Excel for display message ability

caa*_*aax 1 excel vba

I have some VBA code in Excel that allows me to view the contents of a cell when I select it. Here's an example:

单元格选择示例

Here is the code for this:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
With Selection.Validation
.Delete
.Add Type:=xlValidateInputOnly, AlertStyle:=xlValidAlertStop, Operator _
:=xlBetween
.InputMessage = Target.Text
.IgnoreBlank = True
.InCellDropdown = True
.ShowInput = True
.ShowError = True
End With
End Sub
Run Code Online (Sandbox Code Playgroud)

However, when I select a merged cell, I am getting the following error:

错误信息

How can I run this code to work on merged cells?

Vit*_*ata 5

.InputMessage = Target.Text is giving the error. The problem is that the target is multiple cells and these do not have the property Text. A quick fix would be to take the first cell of the target:

.InputMessage = Target.Cells(1).Text
Run Code Online (Sandbox Code Playgroud)

Thus, if it is a single cell it is still the first one and if it is merged, it works ok:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    With Selection.Validation
        .Delete
        .Add Type:=xlValidateInputOnly, AlertStyle:=xlValidAlertStop, Operator:=xlBetween
        .InputMessage = Target.Cells(1).Text
        .IgnoreBlank = True
        .InCellDropdown = True
        .ShowInput = True
        .ShowError = True
    End With
End Sub
Run Code Online (Sandbox Code Playgroud)

  • 同样,`Target(1)`也可以工作。 (3认同)
  • @Vityata,我也不确定自己。也许一个列表框?无论哪种方式,合并的单元格都是一场噩梦:(。请记住许多讨厌的副作用。您的解决方案与IMO一样好。 (2认同)