我创建了一个表单,让用户可以选择7个不同的选项,这些选项都将默认为空白。当他们单击选项旁边的单元格时,它将从空白更改为“是”,再次单击时将删除文本,依此类推。我有它的单元格可以从空白点击到“是”的问题在R33和S33之间合并。代码仅在单元格R33上工作,但在合并它们时却不行。你可以帮我解决这个问题吗?
Private Sub Worksheet_SelectionChange(ByVal Target As Excel.Range)
Application.EnableEvents = False
If Target.Cells.Count = 1 Then
If Not Intersect(Target, Range("R33")) Is Nothing Then
Select Case Target.Value
Case ""
Target.Value = "yes"
Case "yes"
Target.Value = ""
End Select
Range("A1").Select
End If
End If
Application.EnableEvents = True
End Sub
答案 0 :(得分:4)
Private Sub Worksheet_SelectionChange(ByVal Target As Excel.Range)
On Error GoTo Worksheet_SelectionChange_Error
Application.EnableEvents = False
Debug.Print Target.Cells.Count 'just FYI, remove it later
If Not Intersect(Target.Cells(1), Range("R33").MergeArea) Is Nothing Then
Select Case Target.Cells(1)
Case "yes"
Target.Cells(1) = vbNullString
Case vbNullString
Target.Cells(1) = "yes"
End Select
End If
Range("A1").Select
Application.EnableEvents = True
On Error GoTo 0
Exit Sub
Worksheet_SelectionChange_Error:
MsgBox "Error " & Err.Number & " (" & Err.Description & ")
Application.EnableEvents = True
End Sub
合并的单元格在Excel中有点邪恶,但是如果你玩一下就可以实现你所需要的:
Target.Cells.Count
等于合并单元格的数量,因此它永远不会是1
。我删除了它; Target.Cells(1)
是引用MergedArea
; Range("R33").MergeArea
是检查交叉点的好方法; _SelectionChange
事件时,您可能会收到错误,然后离开Application.EnableEvents = False
,最好使用错误捕获器,将其设置回True
;