【问题标题】:Trouble pasting only values in VBA在 VBA 中仅粘贴值时遇到问题
【发布时间】:2015-02-18 05:23:24
【问题描述】:

我试图仅将值粘贴到目标单元格而不是公式,并且经过多次谷歌搜索后没有任何成功。这是我第一次真正涉足 VBA,所以我不确定下一步该去哪里。我当前的代码是:

Function freeCell(r As Range) As Range
' returns first free cell below r
  Dim lc As Range, Tracking As Worksheet     ' last used cell on sheet
  Set lc = r.Offset(40, 6).End(xlUp).Offset(1, 0)
  Set freeCell = lc
End Function


Sub doIt()
  Dim tCell As Range, sh As Worksheet
  Sheets("Bundler").Range("G20").Copy
  Set sh = Sheets(Range("G73").Value)
  Set tCell = freeCell(sh.Range("A3"))
  If tCell.Row < 19 Then Set tCell = tCell.Offset(19 - tCell.Row)
  sh.Paste tCell
End Sub

sh.Paste tCell 粘贴到正确的单元格中,但是如何将其转换为仅值?我知道需要使用 .PasteSpecial xlPasteValues,但我不确定如何格式化它。

【问题讨论】:

    标签: vba excel


    【解决方案1】:
    Sub doIt()
      Dim tCell As Range, sh As Worksheet
      Sheets("Bundler").Range("G20").Copy
      Set sh = Sheets(Range("G73").Value)
      Set tCell = freeCell(sh.Range("A3"))
      If tCell.Row < 19 Then Set tCell = tCell.Offset(19 - tCell.Row)
      tCell.PasteSpecial Paste:=xlPasteValues
    End Sub
    

    【讨论】:

    • 我得到一个编译错误:找不到方法或数据成员
    • @Caminator 最后一行有错字/错误,会引发该错误。尝试修改后的答案。
    【解决方案2】:

    您无需复制和粘贴即可完成此操作:

    Sub doIt()
      Dim tCell As Range, sh As Worksheet
      Set sh = Sheets(Range("G73").Value)
      Set tCell = freeCell(sh.Range("A3"))
      If tCell.Row < 19 Then Set tCell = tCell.Offset(19 - tCell.Row)
      tCell.Formula = Sheets("Bundler").Range("G20").Text
    End Sub
    

    如果您希望将 .text 作为值,请将其更改为 .value

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-27
      • 1970-01-01
      • 2017-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-10
      相关资源
      最近更新 更多