2017-01-14 83 views
-1

在活动范围选择上,如何仅查找包含“0”和“#N/A”的单元格并将其替换为文本“NA”并更改字体颜色为“红色”。如何查找特定单元格并用文本替换

这里是我使用“转换公式绝对值”和“寻找空单元格把文本‘NA’宏。

sub XConvertToValues() 
    Dim MyRange As Range 
    Dim MyCell As Range 
    Set MyRange = Selection 
    For Each MyCell In MyRange 
     If MyCell.HasFormula Then 
      MyCell.Formula = MyCell.Value 
     End If 
     If IsEmpty(MyCell.Value) = True Then 
      MyCell.Value = "NA" 
     End If 
    Next MyCell 
    End Sub 
+0

可以选择多少列? – user3598756

+1

是一个VBA代码的请求?你到目前为止做了什么以及你的具体问题在哪里?也许你会尝试使用录音机并使用搜索功能。 – Storax

+0

我刚更新了我的帖子。我应该更具描述性。 –

回答

1

OP的澄清数据格式

使用Replace()Range对象的AutoFilter()方法后,编辑

Sub XConvertToValues() 
    With Selection 
     .Value = .Value '<--| convert all formulas to their values 
     .Replace What:="#N/A", replacement:="NA", LookAt:=xlWhole 
     .Replace What:="0", replacement:="NA", LookAt:=xlWhole 
     If WorksheetFunction.CountIf(.Cells, "NA") > 0 Then 
      .AutoFilter field:=1, Criteria1:="NA" 
      .Resize(IIf(.Cells(1) = "NA", .Rows.count, .Rows.count - 1)).Offset(IIf(.Cells(1) = "NA", 0, 1)).SpecialCells(xlCellTypeVisible).Font.ColorIndex = 3 
      .Parent.AutoFilterMode = False 
     End If 
    End With 
End Sub 
+0

谢谢 - 这也没有工作。我会再次检查并回到原点。 –

+0

什么“没有工作!”。更明确。并添加数据“之前”和“之后”场景的示例 – user3598756

+0

这仅适用于具有“#N/A”的单元格。如果单元格值为“0”,则不起作用 –

0

编辑

现在,当你有提供更多的信息,这是可以做到这样的:

试试这个

Sub ConvertToValues() 

Dim R As Long 
k = Sheet1.Range("A1048576").End(xlUp).Row '-> total rows in column A 

For R = 1 To k 
If IsEmpty(Sheet1.Cells(R, 2)) = True Or Sheet1.Cells(R, 2) = "#NA" Or Sheet1.Cells(R, 2) = "0" Then 
Sheet1.Cells(R, 2).Value = "NA" 
Sheet1.Cells(R, 2).Font.Color = RGB(255, 0, 0) 

End If 
Next R 
End Sub 

enter image description here

+0

谢谢Ambrish - 我真的是这里的菜鸟。如果能够找到包含“0”和“#N/A”的单元格并将其替换为文本“NA”并将字体颜色更改为“红色”,您能否看到我的VBA代码并帮助我? –

+0

再次感谢Ambrish。我已经尝试过了,这似乎不起作用。我一直无法弄清楚为什么 - 我们在这里错过了一些东西。 –

+0

请注意'Cells(R,1)'也可以写成'Cells(R,“A”)'(我最近只是因为SO上的一些很好的答案才实现的) – YowE3K

0

我是初学者也一样,这个我可以做什么,也许它会帮助你,你可以把你想改变或重写代码的单元格数量设为FOR EACH

Dim i As Integer 

On Error Resume Next 

For i = 1 To 20 

cells.Find(What:="0", MatchCase:=False_, SearchFormat:=False).Activate 
ActiveCell.FormulaR1C1 = "NA" 
With Selection.Font 
    .Color = -16776961 
    .TintAndShade = 0 
End With 

cells.Find(What:="#N/A", MatchCase:=False_, SearchFormat:=False).Activate 
ActiveCell.FormulaR1C1 = "NA" 
With Selection.Font 
    .Color = -16776961 
    .TintAndShade = 0 
End With 
Next i 
+0

这仅适用于 - 只要我们改变'随着Selection.Font 。颜色= -16776961 .TintAndShade = 0 结束With'到'随着ActiveCell.Font 。颜色= -16776961 .TintAndShade = 0 End With# 这不适用于数字“0” –