找到匹配值后,在相应的行

时间:2015-11-18 21:38:48

标签: excel-vba vba excel

每天工作,我有大约400个唯一值,我需要在不同的工作表中搜索该值,并将相应的值拉回原始工作表。我认为我可以自动完成这项工作,因为它对CRTL-F,CRTL-C,CRTL-V每天400次非常繁琐。

为了(尝试)更好地解释这一点,我在下面设置了一个场景:

工作表(" BattleOfEndor&#34)

名称

Han Solo

RedLeader1

RedSquadron1

RedSquadron2

RedSquadron4

BlueLeader1

BlueSquadron4

工作表("反叛联盟人员:船舶和武器偏好")

(假设空格是分栏符)

名称船舶武器

Luke_Skywalker X-Wing Lightsaber

Leia_Skywalker N / A Blaster

Gial_Ackbar Home_One N / A

Han_Solo YT-1300_492727ZED Blaster

RedLeader1 X-Wing Blaster

RedSquadron1 X-Wing Blaster

RedSquadron2 X-Wing Blaster

RedSquadron3 X-Wing Blaster

RedSquadron4 Y-Wing Blaster

RedSquadron5 Y-Wing Blaster

BlueLeader1 Z-95 Blaster

BlueSquadron1 X-Wing Blaster

BlueSquadron2 X-Wing Blaster

BlueSquadron3 Y-Wing Blaster

BlueSquadron4 Y-Wing Blaster

BlueSquadron5 Y-Wing Blaster

因此无论谁是第一个参加战斗的人,我都希望我的代码在我的替代工作表中找到他/她,复制他的船舶价值并将其粘贴到战斗电子表格中的相邻列中,然后转移到下一个人找出他们喜欢飞的船的战斗。

Dim Count As Integer
Dim Target As String

While Count < 433
Count = Count + 1
Target = Worksheets("BattleOfEndor").Range("A2:A433").Cells(Count)

With Worksheets("Rebel Alliance Personnel: Ship and Weapon Preferences").Range("H2:H433")
Dim C As Range
Set C = .Find(Target, LookIn:=xlValues)

我已将上述大部分内容从与.find或.findnext相关的其他答案中复制出来,但我对我接下来的步骤感到难过。

有什么想法吗?我甚至关闭了吗?

1 个答案:

答案 0 :(得分:0)

您无法使用&#34;工作表:&#34;在名称中,

尝试此循环代码,相应地更改工作表的名称。

Sub Button1_Click()
    Dim sh1 As Worksheet, sh2 As Worksheet
    Dim LsRw As Long, Rng As Range, c As Range, x As Range
    Dim Lr As Long, Wrng As Range

    Set sh1 = Sheets("Names")
    Set sh2 = Sheets("Weapons")

    With sh1
        LsRw = .Cells(.Rows.Count, "A").End(xlUp).Row
        Set Rng = .Range("A2:A" & LsRw)
    End With

    With sh2
        Lr = .Cells(.Rows.Count, "H").End(xlUp).Row
        Set Wrng = .Range("H2:H" & Lr)
    End With

    For Each c In Rng.Cells
        For Each x In Wrng
            If x = c Then
                c.Offset(0, 1) = x.Offset(0, 1)
                c.Offset(0, 2) = x.Offset(0, 2)
            End If
        Next x
    Next c

End Sub