运行一个列,如果存在#N / A,直接replace它右边的单元格(Excel VBA)

我试图在Excel中开发一个运行在列中的macros,如果该值指定了#N / A,它将直接将其replace为单元格右侧的单元格。 所以,如果我正在search#N / As的列是H列,那么我将从列I中的下一列将取得的值。下面是我正在尝试构build的代码:

Dim NACol As Range Dim NARange As Range Set NARange = DEV.Sheets("Input File Creator (DND)").Range("H2:H100") Set NACol = .cells.Find(What:="#N/A", _ after:=.Range("H2"), _ lookat:=xlPart, _ LookIn:=xlValues, _ searchorder:=xlByRows, _ searchdirection:=xlPrevious, _ MatchCase:=False).Row For Each NACol In NARange 'Paste the cell directly from the cell to the right Next 

如果这是正确的方法解决这个问题,我卡在For Each。 谢谢!

我认为这是最短和最快的方法,因为它只循环给定范围内的错误单元格。 如果您的错误值是常量而不是公式,则将xlCellTypeFormulas更改为xlCellTypeConstants

 Dim c As Range, NARange as range Set NARange = DEV.Sheets("Input File Creator (DND)").Range("H2:H100") For Each c In NARange.SpecialCells(xlCellTypeFormulas, xlErrors) If Application.IsNA(c) Then c.Value = c.Offset(0, 1).Value Next c 

那么好的和简单的事情呢? 突出显示N / A错误列,然后单击运行。

 Sub Test() Dim c As Range Dim rng As Range Set rng = Selection For Each c In rng Debug.Print c.Value If Application.WorksheetFunction.IsNA(c.Value) Then c.Value = c.Offset(0, 1).Value Next c End Sub 

你的实践对于循环和你的search条件来说都是有点关键的。 假设#N / A值是一个公式错误的结果,这个代码应该清除。

 Dim NARange As Range, CheckCell As Range Set NARange = DEV.Sheets("Input File Creator (DND)").Range("H2:H100") For Each CheckCell In NARange If Application.WorksheetFunction.IsNA(CheckCell) Then CheckCell.Offset(0,1).Copy CheckCell.Select ActiveSheet.Paste 'Doing this rather than value will bring formatting End If Next CheckCell