Excel VBA自定义数字格式填充为零

时间:2019-05-07 09:28:33

标签: excel vba format

寻找VBA在工作表的列中产生此结果:

1.000000

1.000001

1.000002

...

...

1.001000

1.001001

1.001002

它可以是文本或数字。

谢谢。

3 个答案:

答案 0 :(得分:0)

这将特别适合于功能

Public Function replacechar(str As String, charnumber As Integer, replacewith As String) As String

Dim startstr As String, endstr As String

startstr = Left(str, charnumber-1)
endstr = Right(str, Len(str) - Len(startstr))

replacechar = startstr & replacewith & endstr

End Function

例如,您可以在常规Sub中调用此函数

Sub repl()
Dim newstr As String, c As Range

With ThisWorkbook.Sheets(1)
    For Each c In .Range("A1:A100")
        If not c.Value = "" Or Len(c.Value) < 5 Then
            newstr = replacechar(c.Value, 5, "1") 'replaces the 5th char with "1"
            c.Value = newstr
        End If
    Next c
End With

End Sub

答案 1 :(得分:0)

希望这是一个很好的起点:

Sub foo()
    Dim lngCount As Long

    With Sheet1
        For lngCount = 1 To 1002
            .Range("A" & lngCount).NumberFormat = "0.000000"
            .Range("A" & lngCount).Value = 1 + ((lngCount - 1) / 1000000)
        Next lngCount
    End With
End Sub

答案 2 :(得分:0)

可以使用NumberFormatFormula完成此操作。 .Value2 = .Value2将公式转换为实际值

' Update ActiveSheet with your destination sheet reference
' Update .Cells(1,1) with reference to your starting cell - This is A1
' Update Resize(xxx) with the number of cells you want populated
With ActiveSheet.Cells(1, 1).Resize(100)
    .NumberFormat = "0.000000"
    .Formula = "=1 + (row()" & IIf(.Cells(1).Row > 1, " - " & .Cells(1).Row, "") & ") / 1e6"
    .Value2 = .Value2
End With