如何在VBA的xlPasteValues命令中跳过指定单元格保留公式
解决VBA保留指定单元格公式的问题
可以通过暂存目标区域公式再恢复的方式实现需求,同时避免使用Activate和Selection这类易出错的操作,修改后的代码如下:
Dim wsPrintOut As Worksheet Dim formulaRange As Range Dim tempFormulas As Variant ' 复制Report工作表并命名为PrintOut Sheets("Report").Copy Set wsPrintOut = Sheets(1) wsPrintOut.Name = "PrintOut" ' 定位到命名区域PrintOut_Formulas并暂存公式 Set formulaRange = wsPrintOut.Range("PrintOut_Formulas") tempFormulas = formulaRange.Formula ' 将UsedRange全部转换为值 wsPrintOut.UsedRange.Value = wsPrintOut.UsedRange.Value ' 恢复目标区域的公式 formulaRange.Formula = tempFormulas
代码说明:
- 用对象变量
wsPrintOut直接引用工作表,替代Activate和Selection,提升代码稳定性和执行效率。 tempFormulas = formulaRange.Formula把指定区域的公式暂存到数组中,避免粘贴值操作覆盖它们。wsPrintOut.UsedRange.Value = wsPrintOut.UsedRange.Value是直接将单元格转换为值的高效写法,比复制粘贴更简洁。- 最后把暂存的公式写回目标区域,确保这两个单元格保留原有的公式逻辑。
内容的提问来源于stack exchange,提问作者Alec B
相关产品推荐
相关产品推荐

