[英]Copy and paste the row a N number of times (N based on a value in the cell)
[英]Copy & Paste values if cell value = “N/A”
我想將值復制並粘貼到一系列單元格中,但前提是它們的值=“N / A”。 我想將公式保留在所有不是“N / A”的單元格中。
在上下文中,我有數百個VLOOKUP。 例:
=IFERROR(VLOOKUP("L0"&MID(G$4,1,1)&"A0"&MID(G$4,1,1)&MID(G$4,3,2)&"-0"&$B6,Sheet1!$C:$D,2,FALSE),"N/A")
這可能與VBA有關嗎?
首先,您應該使用真正的錯誤值而不是僅看起來像錯誤的字符串。 其次,如果找不到查找值, VLOOKUP
直接返回N/A
錯誤,因此IFERROR
包裝器可以被取消。 所以這個公式
=VLOOKUP("L0"&MID(G$4,1,1)&"A0"&MID(G$4,1,1)&MID(G$4,3,2)&"-0"&$B6,Sheet1!$C:$D,2,FALSE)
足夠了。
要用錯誤值替換N/A
結果,您可以使用它
Sub Demo()
Dim ws As Worksheet
Dim rngSrc As Range
Dim datV As Variant, datF As Variant
Dim i As Long
' Get range to process by any means you choose
' For example
Set ws = ActiveSheet
With ws
Set rngSrc = .Range(.Cells(1, 1), .Cells(.Rows.Count, 1).End(xlUp))
End With
' Copy data to variant arrays for efficiency
datV = rngSrc.Value
datF = rngSrc.Formula
' replace erroring formulas
For i = 1 To UBound(datV, 1)
If IsError(datV(i, 1)) Then
If datV(i, 1) = CVErr(xlErrNA) Then
datF(i, 1) = CVErr(xlErrNA)
End If
End If
Next
' return data from variant arrays to sheet
rngSrc.Formula = datF
End Sub
如果您確實想要使用字符串而不是真正的錯誤值,請調整If
行以適應
您可以使用SpecialCells
縮短與=NA()
單元格的工作,而不是遍歷某個范圍內的所有單元格
這也打開了非VBA方法(如果唯一的錯誤單元格是NA
,即沒有Div#/0
)
NA
細胞的情況 SpecialCells
只關注需要測試的單元格,然后在進行更新之前運行NA
檢查 選項1
手動選擇評估錯誤的公式單元格
選項2
VBA更新評估錯誤的公式單元格
碼
Sub Shorter()
Dim rng1 As Range
On Error Resume Next
' All error formulas in column A
Set rng1 = Columns("A").SpecialCells(xlCellTypeFormulas, 16)
On Error GoTo 0
If rng1 Is Nothing Then Exit Sub
'update with new value (could be value or formulae)
rng1.Value = "new value"
End Sub
選項3
測試=NA()
Sub TestSpecificRegion()
Dim rng1 As Range
Dim rng2 As Range
Dim X
Dim lngRow As Long
On Error Resume Next
' All error formulas in column A
Set rng1 = Columns("A").SpecialCells(xlCellTypeFormulas, 16)
On Error GoTo 0
If rng1 Is Nothing Then Exit Sub
'update with new value (could be value or formulae)
For Each rng2 In rng1.Areas
If rng2.Cells.Count > 1 Then
X = rng2.Value2
For lngRow = 1 To UBound(X, 1)
If X(lngRow, 1) = CVErr(xlErrNA) Then X(lngRow, 1) = "new value"
Next
rng2.Value = X
Else
If rng2.Value2 = CVErr(xlErrNA) Then rng2.Value = "new value"
End If
Next
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.