我正在尝试分配您在 ws4
的 E 列和 F 列中看到的每个 ID...
...分别到 K 列和 L 列中的 wsOutput
上的相应 ID。
我的代码运行没有错误,但没有任何反应。这是我的第一个项目,所以如果这是一个简单的问题,我深表歉意。
我又上网查了一下,发现:
但是,我无法让他们的方法发挥作用。
非常感谢任何帮助!
'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
最佳答案
将源数据放置在名为“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 列的格式相同。建议您首先清洁并修剪 ID 列。因为从图像中可以看到目标工作表中的 ID 列有无法识别的字符。
关于VBA 连接字符串问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39764512/