再会
我的目标是创建一个水平增长的列表(按列)。表1有五列和若干行进行增加,(列A-主任务),(列B-子任务),(列C-资源1执行任务),(列D-资源2执行相同的任务),(E-资源 3 列执行相同的任务)。注意:每个主任务可以有多个子任务,如果是这样,多个单元格(主任务)将被合并以对应于主任务对应的多个子任务。
表2列出了A列中列出的所有资源。这些资源可能已经/未出现在表2(C/D/E列)中,即分配了子任务/主任务。
我的代码旨在搜索表 1 中的每个资源,搜索分配给它的任务和子任务并输出这些结果,如图所示。
代码创建时的计划是:代码必须使用A列中的资源名称-表2作为索引,用它来搜索表1中第一列的资源,如果找到匹配,则输出A列中的值桌子。并继续搜索相同的资源,如果找到则输出。接下来在下一列中搜索相同的资源,然后是下一列。
搜索完资源 aa 后,它会在 c 列中搜索资源 bb,然后是 d,然后是最后一个。实时输入结果值。
非常感谢您对修改我所拥有的内容的帮助。
在下面的代码中,表格位于不同的工作表中。这很好,也可以实施。
Sub SearchResourceNames()
'Declare variables
Dim ws1 As Worksheet, ws2 As Worksheet
Dim r As Range, c As Range, i As Long, j As Long, k As Long
Dim resource As String, task As String, col As Long
'Set the worksheets
Set ws1 = ThisWorkbook.Sheets("Table1")
Set ws2 = ThisWorkbook.Sheets("Table2")
'Initialize variables
i = 2
j = 2
k = 2
col = 2
'Loop through the resources in table 2
For Each r In ws2.Range("A1:A10")
'Get the resource name
resource = r.Value
'Initialize flag to indicate if task has been found
found = False
'Loop through the tasks in table 1
For Each c In ws1.Range("A:A")
'If the resource is found in the current task,
If c.Value = resource Then
'Set the flag to indicate that the task has been found
found = True
'Get the task name
task = c.Offset(0, col).Value
'If the task has not been found before,
If Not ws2.Range("B" & k).Value = task Then
'Add the task name to the output column
ws2.Range("B" & k).Value = task
'Increment the output column index
k = k + 1
End If
End If
Next c
'If the task was not found in any of the tasks,
If Not found Then
'Print a message to the user
MsgBox "The resource " & resource & " was not found in any of the tasks."
End If
Next r
'Move to the next column in table 2
col = col + 1
'Reset the output column index
k = 2
End Sub
数据和期望的输出:
当前不需要的输出