双击以在合并的单元格上插入字符
我想通过双击在特定范围(“A1:A19”)内的单元格内插入或移除“X”。 下面的代码放在项目macros中的“Microsoft Excel Objects \ ThisWorkbook”上。
Private Sub Workbook_SheetBeforeDoubleClick(ByVal Sh As Object, ByVal Target As Range, Cancel As Boolean) If Not Intersect(Target, Range("A1:A19")) Is Nothing Then If Len(Trim(Target)) = 0 Then Target.Value = "X" Cancel = True ElseIf UCase(Trim(Target)) = "X" Then Target.ClearContents Cancel = True End If End If End Sub
此代码适用于未合并的单元格。 但是,我有一个情况,细胞必须合并(2乘2,在列中),在这种情况下,我得到以下错误:
“运行时错误'13'”types不匹配
如何修改代码以防止这种情况?
尝试
Private Sub Workbook_SheetBeforeDoubleClick(ByVal Sh As Object, ByVal Target As Range, Cancel As Boolean) If Not Intersect(Target, Range("A1:A19")) Is Nothing Then If Target.Cells.Count = 1 Then ' handle single cell If Len(Trim(Target)) = 0 Then Target.Value = "X" Cancel = True ElseIf UCase(Trim(Target)) = "X" Then Target.ClearContents Cancel = True End If Else ' handle merged Dim theAddress As String theAddress = Split(Target.Address, ":")(0) & ":" & Split(Target.Address, ":")(0) If Len(Trim(Range(theAddress))) = 0 Then Target.Value = "X" Cancel = True ElseIf UCase(Trim(Range(theAddress))) = "X" Then Target.ClearContents Cancel = True End If End If End If End Sub
当你的单元格被合并时,target会返回一系列的多个单元格,并且正在尝试将值放入单元格中,而不能将值放入。 尝试这个:
Private Sub Workbook_SheetBeforeDoubleClick(ByVal Sh As Object, ByVal Target As Range, Cancel As Boolean) Dim myRange As Range Set myRange = Target.Cells(1, 1) If Not Intersect(myRange, Range("A1:A19")) Is Nothing Then If Len(Trim(myRange)) = 0 Then myRange.Value = "X" Cancel = True ElseIf UCase(Trim(myRange)) = "X" Then Target.ClearContents Cancel = True End If End If End Sub
它返回一个范围参考作为合并范围的左上angular的单元格,并允许您根据该参数input值。