命令将0添加到相关列和单元格 - Excel vba

问题描述 投票:0回答:2

我有2个命令将0添加到数字(8位数,需要9位数),并添加0到手机号码(9位数,以5位数开头,需要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.其他如何将命令返回(即在更改之前)取消?你有办法将其插入另一个代码吗?

提前致谢 ,

excel vba csv
2个回答
0
投票

不确定我完全理解,但你可以使用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


0
投票

Select Case将帮助您满足您的条件:

Sub Add_Zeros()

    Selection.NumberFormat = "@"

    For Each CL In Selection.Cells
        Select Case Len(CL)
            Case 8: CL.value = "0" & CL.Value
            Case 9: CL.value = iif(Left(CL.Value,1)=5,"0","") & CL.value
            Case "" 'do nothing
            Case Else
       End Select
    Next

End Sub

我忽略了问题C有两个原因; 1)因为它不清楚2)每个问题应该只是一个特定的问题。

© www.soinside.com 2019 - 2024. All rights reserved.