将选择转换为前导零格式

Convert selection to Leading zero format

我正在尝试构建一个简单的宏,将选定的数值范围转换为“0000”格式(例如,50,75,888、1000 将是 0050,0075、0888、1000),即它会获取每个值在每个单元格中,并且 returns 一个返回 sheet 的字符串值,然后可以在 Excel

中对其进行操作

差不多了(我想..)我只需要 $format 函数的帮助

Sub LeadingZero()
Dim RngSelected As Range
Dim R As String
Dim RCell As Range
Dim Rrng As Range
Dim RevNum As Long

On Error Resume Next
Set RngSelected = Application.InputBox("Please select a range of cells you want to convert to 0000 format", _
                                          "SelectRng", Selection.Address, , , , , 8)

R = RngSelected.Address
Set Rrng = Range(R)

For Each RCell In Rrng.Cells
    RCell.Value = Format$(RCell, "0000")    'this is the line I want to work!
    'RCell.Value2 = Format$(RCell, "0000")  doesn't seem to work either
    Next RCell
End Sub

谢谢

Sub LeadingZero()
Dim RngSelected As Range
Dim R As String
Dim RCell As Range
Dim Rrng As Range
Dim RevNum As Long

On Error Resume Next
Set RngSelected = Application.InputBox("Please select a range of cells you want to convert to 0000 format", _
                                          "SelectRng", Selection.Address, , , , , 8)

R = RngSelected.Address
Set Rrng = Range(R)

For Each RCell In Rrng.Cells
    RCell.NumberFormat = "000#"
Next RCell
End Sub

感谢 Assaf 和 Dan Donoghue:

Sub LeadingZero2()
'Takes a range with numbers between 1 and 9999 and changes them to text string with "0000" format

Dim RngSelected As Range
Dim RCell As Range
Dim Rrng As Range

On Error Resume Next
Set RngSelected = Application.InputBox("Please select a range of cells you want to convert to 0000 format", _
                                          "SelectRng", Selection.Address, , , , , 8)

Set Rrng = Range(RngSelected.Address)

For Each RCell In Rrng.Cells
RCell.NumberFormat = "@"

RCell = CStr(Array("000", "00", "0")(Len(RCell) - 1) & RCell)

Next RCell

End Sub

您是否特别想通过格式化来完成它?如果你真的想转换值(对查找等有用),那么这个函数会做你想做的。

Function FourDigitValues(InputString As String)
Dim X As Long, MyArr As Variant
MyArr = Split(InputString, ",")
For X = LBound(MyArr) To UBound(MyArr)
    MyArr(X) = Right("0000" & MyArr(X), 4)
Next
FourDigitValues = Join(MyArr, ",")
End Function