VBA:复制时,前面的零被丢弃

问题描述 投票:4回答:6

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

excel vba excel-vba
6个回答
4
投票

导出之前,将该列中的每个单元格转换为文本字段。那应该确保保留每个字符(不要像听起来那样对待数字,而是将其视为数字)。


7
投票

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

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


2
投票

另一种可能性是在每个单元格后面加上一个撇号。这会将所有值都视为文本,这在不同的选项卡将常用值视为文本与数字(即复制与计算)时很有用。

这是通过使用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

0
投票

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

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

此处的方法和按文本格式设置的方法都将导致单元格值仍然在计算中起作用,尽管默认情况下水平对齐方式会有所不同。还请注意,例如,将字符串连接到值将导致差异:

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

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

不过可能是TMI!


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

0
投票

不,@ Mike,当我从系统下载它时,我使用了文本文件,以便其前面始终保持领先的0值。但是,如何将其转换为所需的excel文件并在文件中保留前导零?问题是存在异类序列,有项目04,但也有项目4。如果我同时添加它们,则Excel中的所有前导零将显示不正确。

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