vba搜索范围值,如果值存在则更改每个值?

时间:2017-03-02 10:02:32

标签: excel vba excel-vba

我有一个像这样的电子表格:

Column D        Column G

1               #VALUE!
2               #VALUE!
#VALUE!         3

我正在尝试搜索我的范围值#VALUE!。

如果找到此值,我想更改#VALUE的每次出现!到TBC。

这是我的代码:

    Range("D30:G39").Select
                    Set cell = Selection.Find(What:="#VALUE!", After:=ActiveCell, LookIn:=xlFormulas, _
                    LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
                    MatchCase:=False, SearchFormat:=False)

                    If cell Is Nothing Then
                    'do it something
                    Else

For Each Cell.Value
                    cell.value = "TBC"
Next Cell
'End For

                    wStemplaTE.Range("A41").value = "Please fill in the pallet factor and case size accordingly. Please amend total volume if necessary to accommodate full pallets."
                    End If

我需要尝试创建一个循环,以便每个单元格值都更改为TBC。

我是VBA的新手,并不太确定我会怎么做。

请有人指出我正确的方向/告诉我如何正确地做到这一点?感谢

编辑:

对于每个Cell.Value< ---此行突出显示为红色,因为格式不正确?有什么想法吗?

4 个答案:

答案 0 :(得分:0)

以下是使用Range.Find方法的正确方法,您应该每次都使用它:

(顺便说一句,我已经在很久以前用大块代码中的这种结构回答了你)

Sub test_user7415328()
Dim FirstAddress As String, cF As Range, LookForString As String
LookForString = "#VALUE!"

With ThisWorkbook.Sheets("Sheet's name").Range("D30:G39")
    .Cells(1, 1).Activate
    'First, define properly the Find method
    Set cF = .Find(What:=LookForString, _
                After:=ActiveCell, _
                LookIn:=xlValues, _
                LookAt:=xlWhole, _
                SearchOrder:=xlByRows, _
                SearchDirection:=xlNext, _
                MatchCase:=False, _
                SearchFormat:=False)

    'If there is a result, store the address of the 1st one
    If Not cF Is Nothing Then
        FirstAddress = cF.Address
        Do
            'Do your actions
            cF.Value = "TBC"
            'Keep looking with FindNext method
            Set cF = .FindNext(cF)
        'Look until you find again the first result
        Loop While Not cF Is Nothing And cF.Address <> FirstAddress
    End If
End With

End Sub

答案 1 :(得分:0)

这样做:

Sub Macro1()
Dim Cel, Rng As Range
Set Rng = Range("D30:G39")

For Each Cel In Rng
    If Err.Number = 13 Then Cel.Value = "TBC"
Next

End Sub

答案 2 :(得分:0)

您可以检查Cell的值是否等于CVErr(xlErrValue)

Option Explicit

Sub ReplaceErrVal()

Dim C As Range

For Each C In Range("D30:G39")
    On Error Resume Next
    If C.Value = CVErr(xlErrValue) Then
        If Err.Number <> 0 Then
            On Error GoTo 0
        Else
            C.Value = "TBC"
        End If
    End If
Next

End Sub

答案 3 :(得分:0)

使用

Range("D30:G39").Replace what:="#VALUE!", Replacement:="TBC", lookat:=xlWhole