循环遍历多个范围并根据条件连接

时间:2017-07-24 20:48:08

标签: excel vba range string-concatenation

我有四个具有相同行数的1列范围:国家/地区,名称,类别,金额。 Country,Name和Category范围具有字符串值,Amount范围具有双精度值。我面临的问题是:只要金额高于或低于某个值,我需要在每个类别和每个名称下面获得所有国家/地区的字符串。

样本表:

Country Name Category Amount
croatia Jon Blue 14
norway Jon Blue 23
poland Rob Green 10
egypt Eva Green 8
canada Eva Pink 32
brazil Rob Pink 25
switzerland Rob Pink 35
russia Jon Pink 27
sweden Rob Black 32
togo Rob Black 13
benin Esther Violet 24
morroco Jon Yellow 36
romania Eva Yellow 35
usa Eva Yellow 38
japan Rob Yellow 34

金额> 20,每个类别的正确字符串结果将是:

Blue: Jon: norway(23)
Pink: Eva: canada(32), Rob: brazil(25), switzerland(35)
Yellow: Jon: morroco(36), Eva: romania(35), usa(38), Rob: japan(34)
etc.

知道如何解决这个问题吗?没有写代码,因为我无法弄清楚从哪里开始。正在思考多维数组,但这超出了我的编码能力......任何帮助都非常感激

1 个答案:

答案 0 :(得分:1)

下面的代码可以让您接近您想要的内容。这是输出:

Blue: Jon: norway(23), 

Pink: Eva: canada(32), Pink: Rob: brazil(25), Pink: Rob: switzerland(35), Pink: Jon: russia(27), 
Black: Rob: sweden(32), 
Violet: Esther: benin(24), 
Yellow: Jon: morroco(36), Yellow: Eva: romania(35), Yellow: Eva: usa(38), Yellow: Rob: japan(34), 

你唯一需要做的就是抑制空白的第二行,重复的颜色输出和每行末尾的“,”。但我不想带走你所有的乐趣!如果您遇到问题,请再次发帖。

Option Explicit
Sub test()
Dim r As Range, colorR As Range, resultR As Range
Dim amountR As Range, countryR As Range, nameR As Range
Dim color As String, name As String, country As String, amount As String
Set resultR = Range("A19")
Set r = Range("C2")
Set colorR = r
While r <> ""
  While r = colorR
    Set amountR = r.Offset(0, 1)
    Set nameR = r.Offset(0, -1)
    Set countryR = r.Offset(0, -2)
    If amountR > 20 Then
      If color = r & ": " Or color = "" Then color = "" Else color = r & ": "
      If name = nameR & ": " Then name = "" Else name = nameR & ": "
      country = countryR & "("
      amount = amountR & "), "
      resultR = resultR & color & name & country & amount
    End If
    Set r = r.Offset(1, 0)
  Wend
  If resultR <> "" Then
    resultR = Left(resultR, Len(resultR) - 2)
    Set resultR = resultR.Offset(1, 0)
  End If
  Set colorR = r
Wend
End Sub