如何在Excel中的单个单元格中显示多个值

我对Excel及其function相对比较熟悉,但是对于VBA来说我是非常新的(不过我有MATLAB和C的背景)。 基本上我所拥有的是一张工作表,其中填充每个列标题和填充第一列的员工名称。 该表格包含“训练”的文本值,表示该行中的人在指定列中的设备上训练,或者“否”,表示他们不是。 我想要做的是制作一张单独的表格,第一栏和第一栏中的设备标记为“受过训练”。 理论上,每个单元格将填充该行设备上接受过培训的人员的姓名。 我有一个VBA中的for循环代码,成功地输出到即时窗口的名称

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 

但我已经无法在几个小时的search找出如何在一个单元格中显示这些值。 这可能吗?

提前致谢!

使用连接运算符( & )将值组合成string:

 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 

然后只需将名称放在任何你想要的单元格中。

您必须先select“针对每个人,针对每台机器”还是“针对每台机器针对每个人”。 假设你想用第二个想法去,你可以使用这个伪代码:

 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 

这是基本的想法。 为了获得更好的性能,我将在一些arrays中执行所有这些操作并将其粘贴到一个操作中。