我正在尝试构建一个简单的宏,它将选定范围的数值转换为" 0000"格式(例如50,75,888,1000将是0050,0075,0888,1000),即它获取每个单元格中的每个值,并将字符串值返回到工作表,然后可以在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
由于
答案 0 :(得分:0)
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
答案 1 :(得分:0)
感谢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
答案 2 :(得分:0)
您是否特别希望使用格式化进行操作?如果你真的想转换这个值(对于查找等很有用),那么这个函数就可以做你想要的了。
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