我有这个代码:
Sub NewSummary()
Set ws = ThisWorkbook.Sheets("Sheet1")
iWorking = 3
iTotal = 4
dPercent = iWorking / iTotal
pPercent = Format(dPercent, Percent)
sWorking = iWorking & " / " & iTotal
sWorking = Format(sWorking)
ws.Cells(1, 1).Value = sWorking
ws.Cells(2, 1).Value = pPercent
End Sub
我期望的输出是:
3/4, 75.00%
但我得到的是:
3 月 4 日,0.75
Excel 覆盖“3/4”字符串并假设我想要一个日期。我该如何压制它?为什么 Format 函数不能将 0.75 转换为 75.00%?
最佳答案
你不能格式化这样的字符串。 /
周围的空格是一个问题,但更一般地说,格式化 "3/4"
因为字符串文字依赖于一些隐式类型转换,在这种情况下,它被假定为日期字符串(在美国语言环境中表示 3 月 4 日),这就是为什么你会得到类似日期的结果。
简单地做:
Option Explicit
Sub NewSummary()
Dim ws As Worksheet
Dim iWorking As Long, iTotal As Long
Dim dPercent As Double
Set ws = ThisWorkbook.Sheets("Sheet1")
iWorking = 3
iTotal = 4
dPercent = iWorking / iTotal
ws.Cells(1, 1).Value = Format(dPercent, "0.00%")
End Sub
关于excel - VBA 格式化函数被忽略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57526473/