连接字符串的VBA问题

时间:2016-09-29 07:56:17

标签: vba concatenation

我正在尝试分配您在ws4的E和F列中看到的每个ID ...

enter image description here

...分别在我的wsOutput列K和L中的相应ID。

enter image description here

我的代码在没有错误的情况下运行,但没有任何反应。这是我的第一个项目之一,所以如果这是一个直截了当的问题我会道歉。

我还咨询了互联网并发现:

然而,我无法使他们的方法有效。

非常感谢任何帮助!

'Previous Code
'wsOutput -> Filter Sheet - Worksheet (TARGET) ; ws4 = Search Skills - Worksheet (SOURCE)
Dim separator As String, PreviousResultCG As String, NewResultCG As String, PreviousResultCategory As String, NewResultCategory As String

If separator = "" Then separator = " , "

'lRowInput = ws4.Range("A" & Rows.Count).End(xlUp).row - from above
lRowOutput = wsOutput.Range("A4:A" & Rows.Count).End(xlDown).row


With ws4

    'For each ID on the Source-Worksheet
    For Each ID In .Range("A2:A" & lRowInput)

        'Find the respective ID on Target-Worksheet
        Set FindID = wsOutput.Range("A4:A" & lRowOutput).Find(what:=ID, LookIn:=xlValues, lookat:=xlWhole)

        'Get all CG ID's for the supplier and add them to previously found ID's of that supplier
        If FindID = ID Then

            PreviousResultCG = wsOutput.Range("K" & FindID.row).value

            NewResultCG = PreviousResultCG & separator & .Range("E" & ID.row)

            wsOutput.Range("K" & ID.row).value = NewResultCG


            PreviousResultCategory = wsOutput.Range("L" & FindID.row).value

            NewResultCategory = PreviousResultCategory & separator & .Range("F" & ID.row)

            wsOutput.Range("L" & FindID.row).value = NewResultCategory

        End If

    Next ID

End With

1 个答案:

答案 0 :(得分:1)

将源数据放在名为“source”的工作表中,并创建另一个工作表,您要在其中查找名为“target”的源数据中的值。保留图像中显示的列。

在模块中粘贴下面提到的代码。

Sub look_values()

Dim id, source_id As Range
Dim data_row_num, id_row_num As Long
Dim source_sheet, target_sheet As Worksheet
Dim cg, cat As String

Set source_sheet = ThisWorkbook.Sheets("source")
Set target_sheet = ThisWorkbook.Sheets("target")
Set id = target_sheet.Range("A2")

Do Until id.Value = ""

    source_sheet.Activate
    Range("A1").Activate
    Set source_id = Range("A:A").Find(what:=id.Value, LookIn:=xlValues, lookat:=xlWhole)
    On Error Resume Next
    cg = Cells(source_id.Row, 5).Value
    On Error Resume Next
    cat = Cells(source_id.Row, 6).Value
    target_sheet.Activate
    Cells(id.Row, 11).Value = cg
    Cells(id.Row, 12).Value = cat
    Set id = id.Offset(1, 0)
Loop

End Sub

在运行宏之前,请确保两个工作表上的ID列格式相同。建议你去First Clean&修剪ID列。因为在图像中可以看到目标工作表中的ID列具有无法识别的字符。