VBA:粘贴值而不是公式

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

我是vba的新手。我想使用以下代码将单元格中的某些值从一个选项卡复制到另一个选项卡。

Sheets("Equities").Select
Range("B5").Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlToRight)).Select
Selection.Copy
Sheets("ZSM").Select
Range("B5").Select
ActiveSheet.Paste
Sheets("Bonds").Select
Range("B5").Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlToRight)).Select
Selection.Copy
Sheets("ZSM").Select
Range("B5").Select
Selection.End(xlDown).Select
Selection.End(xlToRight).Select
ActiveCell.Offset(1, 1).Select
ActiveSheet.Paste

这工作正常,直到我想以某种方式修改代码,以便我的vba代码也可以从公式(例如“= J5 * K24”)复制值(我真的只想要公式给出的值)。即使我按以下方式修改代码,这也无效:

Sheets("Equities").Select
Range("B5").Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlToRight)).Select
Selection.Copy
Sheets("ZSM").Select
Range("B5").Select
ActiveSheet.PasteSpecial               ###here
Sheets("Bonds").Select
Range("B5").Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlToRight)).Select
Selection.Copy
Sheets("ZSM").Select
Range("B5").Select
Selection.End(xlDown).Select
Selection.End(xlToRight).Select
ActiveCell.Offset(1, 1).Select
ActiveSheet.PasteSpecial                  ##here

有任何想法吗?我读了一下PasteSpecial方法,但是在这个阶段无法将它应用到我的问题中。

谢谢您的帮助!!

excel vba excel-vba excel-2010
1个回答
4
投票

忘记PasteSpecial xlValues并执行直接值转移,从而完全绕过剪贴板。

dim zsm as worksheet

set zsm = workSheets("ZSM")

with workSheets("Equities")
    with .Range(.range(.cells(5, "B"), .cells(.rows.count, "B").end(xlup)), _
                .range(.cells(5, "B"), .cells(5, .columns.count).end(xltoleft)))
        zsm.cells(5, "B").resize(.rows.count, .columns.count) = .value
    end with
end with

with workSheets("Bonds")
    with .Range(.range(.cells(5, "B"), .cells(.rows.count, "B").end(xlup)), _
                .range(.cells(5, "B"), .cells(5, .columns.count).end(xltoleft)))
        zsm.cells(zsm.rows.count, "B").end(xlup).offset(1, 1).resize(.rows.count, .columns.count) = .value
    end with
end with

你确定最后一个偏移应该是偏移(1,1)而不是偏移(1,0)吗?

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