Excel 使用VBA将邮政编码的前导零添加并维护到CSV
我有一个csv文件,发送给我的邮政编码格式缺少前导零。有些是五位数格式,有些是九位数格式,我不需要包括破折号 我需要添加前导零并将其保存为csv,以保持前导零Excel 使用VBA将邮政编码的前导零添加并维护到CSV,excel,vba,csv,leading-zero,Excel,Vba,Csv,Leading Zero,我有一个csv文件,发送给我的邮政编码格式缺少前导零。有些是五位数格式,有些是九位数格式,我不需要包括破折号 我需要添加前导零并将其保存为csv,以保持前导零 Columns(15).Select Selection.NumberFormat = "@" Dim ThisCell As Range For Each ThisCell In Selection If Len(ThisCell) <= 5 Then ThisCell = "'" & Right
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
列(15)。选择
Selection.NumberFormat=“@”
将此单元格设置为范围
对于选择中的每个ThisCell
如果Len(ThisCell)支持我的评论,我会按照这些思路编写代码。我也会像罗恩说的那样检查,检查它们之前被扔到哪里
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
子测试填充()
将r设置为Excel.Range
尺寸c为Excel.Range
Application.Calculation=xlCalculationManual
设置r=ThisWorkbook.Worksheets(“TestData”).Range(“a1:a10000”)
对于r.单元格中的每个c
c、 value=“””和PadString(c.Text)
下一个c
Application.Calculation=xlCalculationAutomatic
端接头
函数PadString(strInput作为String)作为String
作为布尔值的dimb
作为字节的Dim l
b=长度(条纹)<5
l=IIf(b,5,10)
PadString=Right(字符串(l,“0”)和strInput,l)
端函数
如果可能,尽量避免选择。尝试设置一个范围,因此对工作表中的每个ThisCell(“测试”)使用类似于的范围。范围(“a1:a10000”)
使用文本编辑器(如记事本或记事本++)检查CSV文件。CSV文件真的缺少前导零吗?或者导入CSV文件时excel是否正在删除它们?如果是后者,请确保将导入的zipcode列指定为text类型(在将其写入工作表之前的导入过程中)。以及如何在CSV文件中格式化9位Zipcode。