英文:
Unprotected Excel Sheet Runtime 1004 error - can't set numberformat of Range
问题
I have a simple sub running on togglebutton click as part of a larger vba project. Neither the workbook or sheet are protected. I want to set the format of an output cell (E18 on the same sheet as the button) to match the units the formula is calculated in. The errors occur on the commented-out lines. Without the format lines the sub and the larger project both work perfectly fine.
Private Sub ToggleButtonLB_Click()
If ToggleButtonLB.Value = True Then
ToggleButtonLB.Caption = "kg"
'Range("E18").NumberFormat = "0.0 kg"
Else
ToggleButtonLB.Caption = "lb"
'Range("E18").NumberFormat = "0.0 lb"
End If
End Sub
Any help would be greatly appreciated!
英文:
I have a simple sub running on togglebutton click as part of a larger vba project. Neither the workbook or sheet are protected. I want to set the format of an output cell (E18 on the same sheet as the button) to match the units the formula is calculated in. The errors occur on the commented-out lines. Without the format lines the sub and the larger project both work perfectly fine.
Private Sub ToggleButtonLB_Click()
If ToggleButtonLB.Value = True Then
ToggleButtonLB.Caption = "kg"
'Range("E18").NumberFormat = "0.0 kg"
Else
ToggleButtonLB.Caption = "lb"
'Range("E18").NumberFormat = "0.0 lb"
End If
End Sub
Any help would be greatly appreciated!
答案1
得分: 1
Here is the translated code portion:
如果你运行宏录制器并更改单元格为所需格式,你会得到:
Selection.NumberFormat = "0.0 ""kg"""
因此,在你的代码中,请尝试:
Private Sub ToggleButtonLB_Click()
If ToggleButtonLB.Value = True Then
ToggleButtonLB.Caption = "kg"
Range("E18").NumberFormat = "0.0 ""kg"""
Else
ToggleButtonLB.Caption = "lb"
Range("E18").NumberFormat = "0.0 ""lb"""
End If
End Sub
英文:
If you run the macro recorder and change the cell to your desired format, you will get:
Selection.NumberFormat = "0.0 ""kg"""
So in your code, try:
Private Sub ToggleButtonLB_Click()
If ToggleButtonLB.Value = True Then
ToggleButtonLB.Caption = "kg"
Range("E18").NumberFormat = "0.0 ""kg"""
Else
ToggleButtonLB.Caption = "lb"
Range("E18").NumberFormat = "0.0 ""lb"""
End If
End Sub
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论