首页 > 解决方案 > 循环,查找具有值的单元格,然后在列中搜索相同的单元格并更改其值

问题描述

详细问题

我正在尝试编写一个循环通过 D 列的 VBA 代码,

如果找到 Cells(i,"D") = "Good" 则代码将在整个 D 列中搜索单元格 (i,"D") 中的值并将其所有值更改为 "Good"


这是代码之前的图像。

在此处输入图像描述

这是代码后的图像。

在此处输入图像描述

我的尝试:

Dim i As Integer
For i = 1 To Rows.Count


If Cells(i, "m") = "Good" Then

x = Cells(i, "m")

Next i

我认为您必须存储该值( ID Number ),然后搜索我分配为“X”的值。一旦找到“X”,将状态更改为“良好”

标签: excelvba

解决方案


可能有点复杂,但这里有一个想法。

Sub f(strSearchFor as string)

Dim r As Excel.Range
Dim d As New Scripting.Dictionary

Set r = Range("a1:b10")

For Each c In r.Columns(2).Cells

    If StrComp(c.Value, strSearchFor, vbTextCompare) = 0 Then

        If Not d.Exists(c.Value) Then
            d.Add c.Offset(0, -1).Value, c.Value
        End If

    End If

Next c

For Each c In r.Columns(1).Cells

    If d.Exists(c.Value) Then
        c.Offset(0, 1).Value = d(c.Value)
    End If

Next c


Set r = Nothing
Set d = Nothing

End Sub

推荐阅读