VBA:复制之后前面的零丢弃

时间:2009-01-29 22:31:08

标签: excel vba excel-vba

我正在使用VBA创建Excel文件的副本。在该文件中,有一列包含前面为零的数字。创建文件的副本,但删除此列中的数据。我需要保留前面的零值。如何使用VBA解决此问题?

5 个答案:

答案 0 :(得分:7)

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

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

答案 1 :(得分:4)

在导出之前,将该列中的每个单元格转换为文本字段。这应该确保每个角色都被保留(并且不会被视为一个数字,这听起来就是这样)。

答案 2 :(得分:2)

另一种可能性是在每个细胞附加一个叛徒。这会将所有值视为文本,当不同的标签将常用值视为文本与数字(即以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

答案 3 :(得分:0)

鉴于已接受的答案,它可能不是您所需要的,但设置自定义数字格式也会使前面的零回到显示的值。

要显示前导零到8位的值,例如,将格式设置为00000000,则123将显示为00000123。

此处的方法和format-as-text方法都将导致单元格值在计算中仍然有效,但默认情况下水平对齐方式会有所不同。另请注意,例如,将字符串连接到值将导致差异:

作为文本:显示00000123,附加“x”以获取00000123x

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

可能是TMI!

答案 4 :(得分:0)

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

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