Excel vba - 如何替换具有复杂值的单元格

时间:2017-01-26 18:37:49

标签: excel vba excel-vba

我有两张纸。 WIRES和BOM。

WIRES看起来像这样:

| Ltg-Nr_ | Kurzname | Pin | Kurzname | Pin | Farbe |
|---------|----------|-----|----------|-----|-------|
|  712001 | AJ4      |  11 | LSTS     |   7 | GE    |
|  712002 | AJ4      |  10 | LSTS     |   8 | SW    |
|  712003 | KM_23.1  |   1 | KM_12.4  |   1 | BR    |
|  712004 | AJ4      |  19 | GSR2     |   2 | GN    |
|  712005 | AJ4      |  18 | GSR2     |   1 | SW    |
|  712006 | AJ4      |  46 | CR_31AB  |   1 | BR    |
|  712007 | AJ4      |  49 | CR_CANP  |   1 | OR/SW |
|  712008 | AJ4      |  50 | CR_CANM  |   1 | OR/BR |

BOM看起来像这样:

| Con  |
|------|
| GSR2 |
| AJ4  |

我想在Excel中执行宏来搜索工作表BOM中的行,工作表WIRES中的每个值,以及找到要用value_“cell_in_front_of_it”替换的值的位置。在此之后将1放在细胞面前更换。 例如,它必须在表WIRES中搜索GSR2,并在其中找到GSR2以用GSR2_2替换它;下一行用GSR2_1替换GSR2。 在宏运行之后我希望表看起来像这样:

| Ltg-Nr_ | Kurzname | Pin | Kurzname | Pin | Farbe |
|---------|----------|-----|----------|-----|-------|
|  712001 | AJ4      |  11 | LSTS     |   7 | GE    |
|  712002 | AJ4      |  10 | LSTS     |   8 | SW    |
|  712003 | KM_23.1  |   1 | KM_12.4  |   1 | BR    |
|  712004 | AJ4      |  19 | "GSR2_2" | "1" | GN    |
|  712005 | AJ4      |  18 | "GSR2_1" | "1" | SW    |
|  712006 | AJ4      |  46 | CR_31AB  |   1 | BR    |
|  712007 | AJ4      |  49 | CR_CANP  |   1 | OR/SW |
|  712008 | AJ4      |  50 | CR_CANM  |   1 | OR/BR |

我试过了:

我试过这样的事情:

Sub Macro1()
'
' Macro1 Macro
'

'
Dim Col As Integer
Dim Row As Integer

For Col = 2 To 4
    For Row = 2 To 10
    colo = Row + 1
    Rows = Row + 1
    Sheets("WIRES").Columns(2).Replace What:=Sheets("BOM").Cells(Row, 1).Text, Replacement:=Sheets("WIRES").Cells(Row, 2).Text & "_" & Sheets("WIRES").Cells(Rows, colo).Text, LookAt:=xlWhole, _
    SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
    ReplaceFormat:=False
    Next Row
Next Col

End Sub

1 个答案:

答案 0 :(得分:0)

我做了这个,它完全符合我的要求。 谢谢你的回答。

Dim roww, rowb As Integer
For roww = 2 To 150
    For rowb = 1 To 10

        Sheets("WIRES").Select
        Cells(roww, 2).Select

        If Selection.Value = Sheets("BOM").Cells(rowb, 1).Value Then
                Selection.Value = Selection.Value & "_" & Selection.Offset(0, 1)
                Selection.Offset(0, 1).Value = "1"
        End If

        Sheets("WIRES").Select
        Cells(roww, 4).Select

        If Selection.Value = Sheets("BOM").Cells(rowb, 1).Value Then
                Selection.Value = Selection.Value & "_" & Selection.Offset(0, 1)
                Selection.Offset(0, 1).Value = "1"
        End If

    Next rowb
Next roww