【问题标题】:combine and write out a combination in VBA在 VBA 中组合并写出组合
【发布时间】:2016-07-14 21:44:22
【问题描述】:

我已经编写了一些代码来读取非连续值的数组或组合列表。数组通过将数组的值写入由逗号分隔的字符串变量来写出,即 (mystring = Join(Pie, ",")它们之间没有任何东西。组合效果更好,因为但我不知道如何将组合的内容写到单个单元格中。即组合是水果列表。如果它们是重复的,那么我不知道想将它包含在输出中。我有唯一的值代码工作,但我最终可能会得到一个输出,如 Apple、Orange、Grape、、、Peach。当我使用组合时,值被正确读入,但我我想把它写成只有由逗号分隔的唯一值,即(Apple,Orange,Grape,Peach)任何帮助都会很棒。如有必要,我可以提供一些示例代码。我只需要一些关于如何使用和操作组合的帮助在 Excel VBA 中。(如果可能的话,我什至想按字母顺序对组合中的项目进行排序)提前nks。

【问题讨论】:

标签: arrays excel vba combinations


【解决方案1】:

怎么样:

Dim result As String
Dim fruit As Variant

fruit = Array("Banana", "Apple", "Banana", "Orange", "", "Apple")

For i = 0 To UBound(fruit)

    If fruit(i) <> "" And InStr(result, fruit(i)) = 0 Then
        If result <> "" Then
            result = result + ", " + fruit(i)
        Else
            result = fruit(i)
        End If
    End If
Next i

MsgBox result 'returns: "Banana, Apple, Orange"

编辑:如果水果存储在工作表上,只需循环遍历单元格并将它们添加到数组中。

编辑 2.0:

Dim result As String
Dim fruit As Variant, allfruits As Variant
Dim i As Integer
Dim success As Boolean

allfruits = Array("Apple", "Orange", "Mango", "Banana")   'Fruits sorted by Importance
fruit = Array("Banana", "Apple", "Banana", "Orange", "", "Apple")

For i = 0 To UBound(allfruits)
    success = False
    For Each element In fruit
        If element = allfruits(i) And success = False Then
            success = True
        End If
    Next element
    If success = True Then
        If result = "" Then
            result = allfruits(i)
        Else
            result = result + ", " + allfruits(i)
        End If
    End If
Next i

MsgBox result 'returns: "Apple, Orange, Banana"

【讨论】:

  • 效果很好。最后,我想参考一个值的查找表,比如 1-10,并从 1-10 对数组的项目进行排序。 IE。如果 Apple = 5 且 Banana = 2 且葡萄 = 9,则数组将重新排序为“香蕉、苹果、葡萄”。该查找表在另一张纸上,但如果需要在 VBA 中使用静态值对其进行硬编码,我可以。谢谢。
  • 1.你能张贴一张你的意思查找表的图片吗?其次,你的意思是水果应该按值排序(最小的在前,...,最大的值在后)?
  • 无权访问。在单独的工作表上,我有一个以特定顺序排列的 10 种水果的列表,我希望根据该单独工作表中的表格以特定顺序将其列在数组中。即第 1 行第 B 列 = 1 和第 1 行第 C 列 = 苹果,然后在下面的 1 行,我有 2 和梨,然后是 3 和橙色,依此类推......这张表规定了水果在数组中列出的顺序。换句话说,如果 Pear 在构建阵列时首先出现,它将被添加到阵列中,那么如果 Apple 在 pear 之后出现,我希望它在阵列中的 Pear 之前。希望这有助于解释它。感谢您的帮助。
  • 十种果子都是“可能”的果子吗?
  • 是的,列表是静态的,它们都是可能的。我遍历一个“一袋好东西”,如果袋子里有 4 个水果,那么我希望它们以特定的顺序展示,而不管它们从袋子中取出的顺序如何。提前谢谢。
猜你喜欢
  • 2014-11-15
  • 2016-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-22
  • 2013-05-25
  • 2019-06-08
相关资源
最近更新 更多