我正在尝试创建一个宏,只需按下相应的快捷键,就可以在不同的格式之间循环。我创建的代码如下:
Option Explicit
Sub FormatCycle()
'
' FormatCycle Macro
'
' Keyboard Shortcut: Ctrl+Shift+E
'
If Selection.NumberFormat = "General" Then
Selection.NumberFormat = "#,##0.00_);(#,##0.00)"
ElseIf Selection.NumberFormat = "#,##0.00_);(#,##0.00)" Then
Selection.NumberFormat = "0.00%_);(0.00%)"
ElseIf Selection.NumberFormat = "0.00%_);(0.00%)" Then
Selection.NumberFormat = "#,##0.00""x"";(#,##0.00""x"")"
ElseIf Selection.NumberFormat = "#,##0.00""x"";(#,##0.00""x"")" Then
Selection.NumberFormat = "General"
Else
Selection.NumberFormat = "General"
End If
End Sub除了第二种类型的带有负值的格式(即(#,##0.00))之外,一切都可以正常工作。当我单独使用这种格式时,例如通过自定义格式化一个泛型单元格,它就完成了它的工作,并在括号中显示负数。然而,在宏中,当我运行它时,它以“常规”格式显示数字,例如-12.00而不是(12.00)。
我搞错了什么?
发布于 2019-07-07 22:57:48
对于要在括号中显示的负数,请尝试用引号括起来,如NumberFormat = "0;(""$0,000"")“
发布于 2019-07-08 00:21:59
我也看到了-12.00和Selection.NumberFormat,但当我切换到Selection.NumberFormatLocal时,我开始看到(12.00)。因此,我建议将代码中的Selection.NumberFormat替换为Selection.NumberFormatLocal。
类似于:
Option Explicit
Sub FormatCycle()
'
' FormatCycle Macro
'
' Keyboard Shortcut: Ctrl+Shift+E
'
Dim currentCell As Range
On Error Resume Next
Set currentCell = Selection
On Error GoTo 0
If currentCell Is Nothing Then Exit Sub ' Could probably check if TypeName is a range
With currentCell
Select Case .NumberFormatLocal
Case "General"
.NumberFormatLocal = "#,##0.00_);(#,##0.00)"
Case "#,##0.00_);(#,##0.00)"
.NumberFormatLocal = "0.00%_);(0.00%)"
Case "0.00%_);(0.00%)"
.NumberFormatLocal = "#,##0.00""x"";(#,##0.00""x"")"
Case "#,##0.00""x"";(#,##0.00""x"")"
.NumberFormatLocal = "General"
Case Else
.NumberFormatLocal = "General"
End Select
End With
End Sub另一件事是,您实际上是在循环遍历预定义的数字格式列表( IF语句中的每个分支都是在前一个分支中分配的分支)。因此,最好将要循环通过的所有数字格式存储在一个数组中,然后查找当前数字格式(在数组中)的位置,并返回它后面的数字格式。这样,如果您希望在循环中引入更多数字格式,而不是手动添加更多If Else或Case分支,则只需将新条目添加到数组中。
另一方面,如果您当前的方法很好,并且这只是一个快速的宏,那么就不需要修复没有损坏的部分。
https://stackoverflow.com/questions/56922935
复制相似问题