我认为这是一个独特的问题,我需要帮助。
这段代码不起作用,但我希望有一个语法可以工作,我还需要知道把它放在哪里。
在哪个事件中以及在什么级别的代码(模块或ThisWorkbook或工作表)?
或者可以在 Excel 中使用某种类型的条件格式来完成此操作吗?
If Cells.Value = 0 Then
Cells.NumberFormat = "0"
ElseIf Abs(Cells.Value) > 0 And Abs(Cells.Value) < 0.1 Then
Cells.NumberFormat = "0.000"
ElseIf Abs(Cells.Value) >= 0.1 And Abs(Cells.Value) < 1 Then
Cells.NumberFormat = "0.00"
ElseIf Abs(Cells.Value) >= 1 And Abs(Cells.Value) < 10 Then
Cells.NumberFormat = "0.0"
ElseIf Abs(Cells.Value) >= 10 Then
Cells.NumberFormat = "0"
End If
谢谢, 戴尔
Module1
。.xlsm
或 .xlsb
扩展名保存文件,才能将代码保留在工作簿中。Option Explicit
Sub FormatCellsWithNumbers()
Const SECONDS_PER_100k As Long = 25 ' depends on the computer
Const WARNING_CELLS_COUNT As Long = 100000
Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
' If it isn't, reference it by its name or use 'ActiveWorkbook'.
' Count the number of cells with numbers.
Dim CellsCount As Double: CellsCount = CellsWithNumbersCount(wb)
If CellsCount > WARNING_CELLS_COUNT Then
Dim msg As Long: msg = MsgBox("Found " & Format(CellsCount, "#,##0") _
& " cells with numbers." & vbLf _
& "Formatting that many cells will take about " _
& Format(CellsCount / 100000 * SECONDS_PER_100k, "#,##0") _
& " seconds." & vbLf & vbLf & "Do you want to continue?", _
vbQuestion + vbYesNo + vbDefaultButton2, "Long Operation!")
If msg = vbNo Then Exit Sub
End If
' Start measuring the time passed.
Dim t As Double: t = Timer
Application.ScreenUpdating = False ' increase efficiency
' Declare additional variables.
Dim ws As Worksheet, cell As Range, FormattedCellsCount As Long
' Loop through all worksheets and format cells containing numbers.
For Each ws In wb.Worksheets
For Each cell In ws.UsedRange.Cells
FormatCellWithNumber cell, FormattedCellsCount
Next cell
Next ws
Application.ScreenUpdating = True
' Inform.
MsgBox Format(FormattedCellsCount, "#,##0") _
& " cells with numbers formatted in " _
& Format(Timer - t, "0") & " seconds.", vbInformation
End Sub
Function CellsWithNumbersCount(ByVal wb As Workbook) As Double
Dim ws As Worksheet, cell As Range, CellsCount As Long
For Each ws In wb.Worksheets
For Each cell In ws.UsedRange.Cells
If VarType(cell.Value) = vbDouble Then CellsCount = CellsCount + 1
Next cell
Next ws
CellsWithNumbersCount = CellsCount
End Function
Sub FormatCellWithNumber(ByVal cell As Range, ByRef FormattedCellsCount As Long)
Dim Value As Variant: Value = cell.Value
Dim NumFormat As String
If VarType(Value) = vbDouble Then ' is a number
FormattedCellsCount = FormattedCellsCount + 1
Select Case Abs(Value)
Case 0, Is >= 10: NumFormat = "0"
Case Is < 0.1: NumFormat = "0.000"
Case Is < 1: NumFormat = "0.00"
Case Is < 10: NumFormat = "0.0"
End Select
cell.NumberFormat = NumFormat
'Else ' not a number
End If
End Sub