【问题标题】:Retaining Leading Zero when Copy & Pasting复制和粘贴时保留前导零
【发布时间】:2020-02-19 17:44:45
【问题描述】:

我有以下代码,可以将数据从一张纸复制并粘贴到另一张纸上。

如果您需要更多详细信息: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

【问题讨论】:

  • 更改列的.NumberFormat 不起作用吗?
  • 很有可能,前导零只是值的字符串表示形式的一部分,而不是值本身的一部分。因此,没有要保留的前导零。我会选择@BigBen 并相应地设置NumberFormat
  • @BigBen 我只是不确定在哪里添加 .NumberFormat = "@" 与代码。当我添加它时,我只会收到一条错误消息。

标签: excel vba split formatting delimiter


【解决方案1】:

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

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)

两者都会做你想做的。

【讨论】:

  • 啊完美,我把它添加到错误的地方!你是明星!
猜你喜欢
  • 2022-07-15
  • 2017-05-17
  • 2013-09-22
  • 2017-05-08
  • 2021-04-28
  • 2016-03-31
  • 1970-01-01
  • 1970-01-01
  • 2018-02-16
相关资源
最近更新 更多