使用VBA向CSV添加和维护邮政编码的前导零

我有一个csv文件,该文件是通过邮编发送给我的,邮编的格式缺少前导零。有些采用五位数格式,有些采用九位数格式,对此我不必加破折号。

我需要添加前导零并将其另存为将保持前导零的csv。

Columns(15).Select
Selection.NumberFormat = "@"

Dim ThisCell As Range
For Each ThisCell In Selection
    If Len(ThisCell) <= 5 Then
        ThisCell = "'" & Right("00000" & ThisCell,5)
    Else
        ThisCell = "'" & Right("00000000" & ThisCell,10)
    End If
Next ThisCell

当前,这不会保持前导零,并导致文件冻结,并需要几分钟才能加载到vba中的下一步。

jiangzhiqinjiayou 回答:使用VBA向CSV添加和维护邮政编码的前导零

为支持我的评论,我将按照以下方式编写代码。我还会像罗恩所说的那样检查一下,然后检查一下它们放在哪里。

Sub TestPadding()

Dim r As Excel.Range
Dim c As Excel.Range

Application.Calculation = xlCalculationManual

Set r = ThisWorkbook.Worksheets("TestData").Range("a1:a10000")

For Each c In r.Cells
    c.value = "'" & PadString(c.Text)
Next c

Application.Calculation = xlCalculationAutomatic

End Sub

Function PadString(strInput As String) As String

Dim b As Boolean
Dim l As Byte

b = Len(strInput) < 5
l = IIf(b,5,10)

PadString = Right(String(l,"0") & strInput,l)

End Function
本文链接:https://www.f2er.com/3143029.html

大家都在问