简体   繁体   English

Excel中的SpecialCells返回公式的值

[英]SpecialCells in Excel to return value of a formula

I wanted a quick simple way to copy cell values to another sheet using SpecialCells in Excel as opposed to looping 我想要一种快速简单的方法来使用Excel中的SpecialCells将单元格值复制到另一个工作表,而不是循环

My VBA code is as below: 我的VBA代码如下:

Sub copyMissingData()
    Worksheets("Source").Range("Z4:Z2000").SpecialCells(xlCellTypeConstants).Copy Worksheets("Destination").Range("missing_qbc")
End Sub

My source data Z4:Z20000 has formulas that returns a value (texts/numbers/fraction etc) or blank "". 我的源数据Z4:Z20000具有返回值(文本/数字/分数等)或空白“”的公式。 I want the copy to ignore the blanks, but copy any other value returned 我希望副本忽略空格,但复制其他任何返回的值

The VBA code above using SpecialCells(xlCellTypeConstants) doesn't work because of the formula in the source range. 由于源范围内的公式,因此上面使用SpecialCells(xlCellTypeConstants)的VBA代码不起作用。

My question: Is there a straightforward way I can use range.specialcells to copy my data from a worksheet to another bearing in mind that source cells contain formulas and the formulas may produce empty string cells which will need to be skipped 我的问题:有没有一种简单的方法可以使用range.specialcells将我的数据从工作表复制到另一个表中,请记住源单元格包含公式,并且该公式可能会产生空字符串单元格,因此需要跳过

If you have formulas, why are you trying to select the constants? 如果您有公式,为什么要尝试选择常量?

Use this: 用这个:

Worksheets("Source").Range("Z4:Z2000").SpecialCells(xlCellTypeFormulas, 23).Copy
Worksheets("Destination").Range("missing_qbc").pastespecial(xlPasteValues)

The 23 means "Numbers, Texts, Logicals and Errors". 23表示“数字,文本,逻辑和错误”。

Doing the copy and paste separately ensure blanks are skipped (if that's what you mean by "ignore"). 分别进行复制和粘贴,以确保跳过空白(如果这就是“忽略”的意思)。

Paste values makes sure only the values get pasted, not the formulas themselves. 粘贴值可确保仅粘贴值,而不确保公式本身。

Please note that if you have a formula in a cell, it is not blank. 请注意,如果单元格中有一个公式,则不能为空。 Even if the formula produces an empty string value as a result, the cell itself is not empty! 即使公式产生的结果为空字符串值,单元格本身也不为空! In htat case, you need to do a copy-paste values in place before you do anything else - and even then Excel sometimes doesn't consider blank cells blank. 在这种情况下,您需要先进行复制粘贴值,然后再执行其他操作-甚至Excel有时也不会将空白单元格视为空白。 If this is the case, you need to iterate (loop) through the cells, and copy them one-by-one. 在这种情况下,您需要遍历单元格(循环),并一一复制。

The easiest way I can think of is to remove the blanks after copying all: 我能想到的最简单的方法是在全部复制后删除空白:

Set rngFrom = [Source!Z4:Z2000]
Set rngTo = [Destination!missing_qbc].Resize(rngFrom.Rows.Count, 1)
rngTo.Value = rngFrom.Value
rngTo.SpecialCells(xlCellTypeBlanks).Delete Shift:=xlUp

The more complicated way is with array formula, but doesn't need VBA. 比较复杂的方法是使用数组公式,但不需要VBA。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM