复制和粘贴时保留前导零

问题描述 投票:0回答:1

我有下面的代码,用于将数据从一张纸复制并粘贴到另一张纸。

如果您需要更多详细信息:Offset the Copy Row as part of a Loop

我遇到的主要问题是,一旦拆分成单独的行,就保留大小的前导零。

    COL_SIZE in "SS21 Master Sheet"= 06|612|1218|1824 
    Column "AH" in "Buysheet" is = 6
                                   612
                                   1218
                                   1824

我如何将AH列设置为Text,以使其保留零(06)?我尝试了几种选择,但目前都无法使用。

Private Sub Workbook_Open()

Sheets("BUYSHEET").Cells.Clear


  Const COL_SIZE As String = "AO" 'This is the column with all the sizes listed in the mini master

  Dim wb1 As Workbook, wsSource As Worksheet
  Set wb1 = Workbooks.Open("U:\Design\KIDS\SS21 Kids Miniscale (Master) .xlsm") ' This is the file path to your mini master.
  Dim wb2 As Workbook, wsTarget As Worksheet
  Set wb2 = ThisWorkbook
  Dim iLastRow As Long, iTarget As Long, iRow As Long
  Dim rngSource As Range, ar As Variant, i As Integer

  Set wsSource = wb1.Sheets("SS21 Master Sheet") ' This is the name of your manster tab
  Set wsTarget = wb2.Sheets("BUYSHEET") 'this ths the name of your buysheet tab


  iLastRow = wsSource.Range("A" & Rows.Count).End(xlUp).Row
  iTarget = wsTarget.Range("A" & Rows.Count).End(xlUp).Row

  With wsSource
  For iRow = 1 To iLastRow
     Set rngSource = Intersect(.Rows(iRow).EntireRow, .Range("A:C, E:Y, Z:AF, AH:AI, AO:AO")) 'This columns you want to pull though to the buysheet tab (if one column must still be range eg, AO:AO)
     If iRow = 1 Then
        rngSource.Copy wsTarget.Range("A1")
        iTarget = iTarget + 1
     Else
       ar = Split(.Range(COL_SIZE & iRow), "|")
       For i = 0 To UBound(ar)
           rngSource.Copy wsTarget.Cells(iTarget, 1)
           wsTarget.Range("AH" & iTarget).Value = ar(i) 'AI is the column the sizes will populate in - We want this to replace the size list
           iTarget = iTarget + 1
       Next
     End If
    Next

  MsgBox "Completed"
  End With
excel vba split formatting delimiter
1个回答
0
投票

好,我知道现在发生了什么。

wsTarget.Range("AH" & iTarget).Value = ar(i)

如果写的是06,则Excel会将其视为数字并将其设置为6

您可以像这样“格式化为文本”,之前您要写入值:

With wsTarget.Range("AH" & iTarget)
    .NumberFormat = "@"
    .Value = ar(i)
End With

或者您可以在值前加上撇号/单引号:

wsTarget.Range("AH" & iTarget).Value = "'" & ar(i)

任何人都可以做你想做的。

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