如何循环遍历范围并将值赋给参数

4

我遇到了一个与Excel VBA代码相关的问题,希望有人能帮助我解决。

我有一个Excel列,范围是B2到列B的最后一行,如下所示:

_________________
|Column B Header|
|===============|
|apple          |
|orange         |
|strawberry     |
|blueberry      |
|_______________|

我想将单元格B中的所有值分配给带有一些附加文本的参数。

例如:

fruits = <Item>apple</Item><Item>orange</Item><Item>strawberry</Item><Item>blueberry</Item>

这是我的代码,到目前为止,我很难让每个值在读取每个单元格后继续往后传递。
Dim c As Range
For each c In Range("B2:B" & lastrow)
   fruits = "<Item>" & c.Value & "</Item>"
Next c

如果有人愿意帮助我,我真的非常感激。 谢谢。


7
fruits = fruits & "<Item>" & c.Value & "</Item>" - BigBen
3个回答

3
为了在循环中继续构建字符串,可以将fruits与自身连接起来:
fruits = fruits & "<Item>" & c.Value & "</Item>"

2
或者你可以避免循环。
Dim fruits As String
fruits = "<Item>" & Replace(Join(Application.Transpose(Range("B2", Cells(Rows.Count, 2).End(xlUp)).Value), "|"), "|", "</Item><Item>") & "</Item>"

1

没有循环的函数加上变量标签名称

Function JoinedItems(rng As Range, Optional tag As String = "item") As String
    Dim a$, b$: a = "<" & tag & ">": b = "</" & tag & ">"
    JoinedItems = a & Evaluate("=TEXTJOIN(""" & b & a & """, False," & rng.Address & ")") & b
End Function


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接