首页 > 解决方案 > 命令将 0 添加到相关列和单元格 - Excel vba

问题描述

我有 2 个命令将 0 添加到数字(8 位,需要 9 位)和 0 到手机号码(以 5 位开头的 9 位需要为 10 位):

1.添加0到8位数字:

Sub Add_Zeros()
    Selection.NumberFormat = "@"
    For Each CL In Selection.Cells
        If CL <> "" Then CL.Value = Application.Rept("0", (9 - Len(CL))) & CL
    Next
End Sub

2.添加0到9位数字:

Sub Add_Zeros()
    Selection.NumberFormat = "@"
    For Each CL In Selection.Cells
        If CL <> "" Then CL.Value = Application.Rept("0", (10 - Len(CL))) & CL
    Next
End Sub

我可以升级这些代码并将它们组合如下吗?:

A.第一个条件:如果只有8位就在开头加0(最后应该是9位)

B.第二个条件:如果有9个数字,左边第一个数字是5你在开头加0(最后应该有10个数字)

C.还有什么我如何将命令返回(即更改之前)以取消?你有办法把它插入另一个代码吗?

提前致谢 ,

标签: excelvbacsv

解决方案


不确定我是否完全理解,但您可以使用if elseelseif

Function sort_out_phone(strPhoneIN As String) As String

If Len(strPhoneIN) = 8 Then
    sort_out_phone = "0" & strPhoneIN
ElseIf Len(strPhoneIN) = 9 And Left(strPhoneIN, 1) = "5" Then
    sort_out_phone = "0" & strPhoneIN
Else
    sort_out_phone = "What ever you need to do here"
End If

End Function

sort_out_phone("12345678")=012345678

sort_out_phone("123456789")=你需要在这里做什么

sort_out_phone("523456789")=0523456789


推荐阅读