How to display multiple values in a single cell in Excel
我对 Excel 及其函数比较熟悉,但对 VBA 很陌生(不过我确实有 MATLAB 和 C 的背景)。基本上,我所拥有的是一张表格,其中包含不同的机器填充每个列标题和填充第一列的员工姓名。该表包含文本值"Train",表示该行中的人员在指定列中的设备上接受过培训,或"No",表示他们没有。我想要做的是制作一个单独的表,其中第一列中有设备,一个列标题为"受过训练"。理论上,每个单元格都将填入在该行设备上接受过培训的人员的姓名。我在 VBA 中有一个 for 循环代码,可以成功地将名称输出到即时窗口
1 2 3 4 5 6 7 8 9 10 11 | Function Train(Data As Range, Name As Range) For Counter = 1 To Data.Rows.Count If Data(Counter, 1).Value ="Train" Then 'Debug.Print Name(Counter, 1) End If Next Counter End Function |
但我在几个小时的搜索中无法弄清楚如何在单个单元格中显示这些值。这可能吗?
提前致谢!
您必须首先选择是要执行"针对每个人,针对每台机器"还是"针对每台机器,针对每个人"。假设您想采用第二个想法,您可以使用以下伪代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | set wsEmployee = Worksheets("EmployeeSheet") set wsEmployee = Worksheets("MachineSheet") 'Clear MachineSheet and add headers here xEmployee = 2 yMachine = 2 do while (wsEmployee.Cells(1, xEmployee).Value <>"") 'or your loop way here yEmployee = 2 trained ="" do while (wsEmployee.Cells(yEmployee, 1).Value <>"") 'or your loop way here if (wsEmployee.Cells(yEmployee, xEmployee).Value ="Trained") then trained = trained & wsEmployee.Cells(yEmployee, 1).Value &"," end if yEmployee = yEmployee + 1 loop 'remove the last , in the trained string wsMachine.Cells(yMachine, 1).Value = wsEmployee.Cells(1, xEmployee).Value wsMachine.Cells(yMachine, 2).Value = trained yMachine = yMachine + 1 xEmployee = xEmployee + 1 loop |
这是基本思想。为了获得更好的性能,我会在一些数组中执行所有这些操作并将它们粘贴到一个操作中。
使用连接运算符(
1 2 3 4 5 6 7 8 9 10 11 12 13 | Dim names as String names ="" For Counter = 1 To Data.Rows.Count If Data(Counter, 1).Value ="Train" Then If counter = 1 Then names = names & Name(counter, 1) Else names = names &"," & Name(counter, 1) End If End If Next Counter |
然后将名称放在您想要的任何单元格中。