简体   繁体   中英

Type error on merged cells in Excel for display message ability

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

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

错误信息

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

.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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM