我有下表(Simplyfing)
City Value
paris 1
London 2
Leeds 3
Hanoi 4
Newyork 5
我有这样的条件:If value <= 3 Then
接受并放入一个单元格,如下所示:Paris, London, Leeds
。
如果我使用MsgBox
循环,那么我可以轻松地显示所有内容,但我不知道如何将所有值放入单个单元格
答案 0 :(得分:1)
尝试下面的代码(代码注释中的解释):
Option Explicit
Sub ResultsinSingleCell()
Dim ResultRng As Range
Dim C As Range
Dim LastRow As Long
Dim ResString As String
With Worksheets("Sheet7") ' replace "Sheet7" with your sheet's name
LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row ' <-- get last row in Column "A" (where the list of cities exist)
Set ResultRng = .Range("C2") ' <-- set the range of the result
' loop through all values in column "B"
For Each C In .Range("B2:B" & LastRow).Cells
If C.Value <= 3 Then
If ResString = "" Then '<-- check if string is empty >> first match
ResString = C.Offset(, -1).Value
Else
ResString = ResString & ", " & C.Offset(, -1).Value
End If
End If
Next C
End With
ResultRng.Value = ResString
End Sub
使用样本数据运行代码后进行屏幕截图: