首页 > 解决方案 > 运行时错误“1004”无法设置 Range 类的 NumberFormat 属性

问题描述

我安装了一个非常简单的命令按钮来为选定的单元格添加时间戳。命令按钮完全可以正常工作,直到我保护工作表,然后它会抛出标题中提到的错误。我已经检查过单元格的格式没有选择为“锁定”。

Private Sub CommandButton1_Click()
Dim ts As Date

With Selection

.Value = Now

.NumberFormat = "h:mm AM/PM"

End With
End Sub

标签: excelvba

解决方案


允许格式化单元格

您必须允许格式化单元格。

在此处输入图像描述

或在 VBA 中

ActiveSheet.Protect AllowFormattingCells:=True

推荐阅读