VBA:复制时删除前面的零

我正在使用VBA创build一个Excel文件的副本。 在文件中,有一列包含前面的零的数字。 该文件的副本被创build,但是该列中的数据被删除。 我需要保持与前面的零值。 我怎样才能解决这个问题与VBA?

在导出之前,将该列中的每个单元格转换为文本字段。 这应该确保每个angular色都被保留下来(而不是像一个数字那样对待,这就是发生的事情)。

最好的方法是通过将Range.NumberFormat设置为“@”,将列预先格式化为文本。 这样,如果用户编辑单元格,单元格将保持为文本并保持其前导零。 这是一个VBA的例子:

ActiveSheet.Range(“C:C”)。NumberFormat =“@”

另一种可能性是给每个单元格附加一个apostrphe。 这将把所有的值视为文本,这是有用的,当不同的标签对待常见的值为文本与数字(即复制vs计算)。

这是通过使用Chr()函数并为其分配字符代码39(')来完成的:

For x = 1 to 100 If Sheets(origSheet).Cells(x, "A").Value <> "" Then Sheets(origSheet).Cells(x, "A").Value = Chr(39) & Sheets(origSheet).Cells(x, "A").Value End If 

考虑到接受的答案,这可能不是你所需要的,但是设置一个自定义数字格式也将得到前面的零点返回到显示值。

例如,要显示前导零的数值(最多8位数字),请将格式设置为00000000,然后将123显示为00000123。

这里的方法和format-as-text方法都会导致单元格值在计算中仍然有效,尽pipe默认情况下水平alignment方式会有所不同。 还要注意,例如,将string连接到值将导致不同:

作为文本:显示00000123,附加“x”得到00000123x

作为具有自定义格式的数字:显示00000123,附加“x”得到123x,因为它仍然是一个数字。

虽然可能是TMI!

这是我为解决此问题而创build的代码:

 Public Sub Change_10_Digit() '---------------------------------------------------------------------------- ' Change numeric loan number ot a 10 digit text number ' 2010-05-21 by Jamie Coxe ' ' Note: Insure exracted data Column is formated as text before running macro '---------------------------------------------------------------------------- Dim Lastrow As Long Dim StartRow As Long Dim Col As String Dim RowNum As Long Dim nCol As String Dim Loan As String Dim Digit_Loan As String Dim MyCell As String Dim NewCell As String Dim Cell_Len As Long Dim MyOption As Long '----- Set Options ------------------------------------------------------- MyOption = 2 '1 = place data in new column, 2 = Replace data in cell StartRow = 2 'Start processing data at this row (skip header row) Col = "B" 'Loan number in this colmun to be changed to 10 digit nCol = "G" 'New column to place value (option 1 only) '----- End Option Setings ------------------------------------------------ 'Get last row Lastrow = Range(Col & "65536").End(xlUp).Row For RowNum = StartRow To Lastrow 'Combined Column and Row number to get cell data MyCell = Col & RowNum 'Get data in cell Loan = Range(MyCell).Value 'Change data in cell to 10 digit numeric with leading zeros Digit_Loan = Format(Loan, "0000000000") If My0ption = 1 Then 'Option 1 enter value in new cell NewCell = nCol & RowNum Range(NewCell).Value = Digit_Loan Else 'Option 2 replace value in cell Range(MyCell).Value = Digit_Loan End If Next RowNum End Sub