VBA Excel:连接一系列单元格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25316228/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 08:48:07  来源:igfitidea点击:

VBA Excel: Concatenate a range of cells

excelvbaexcel-vba

提问by DeeWBee

I am trying to concatenate a range of cells along a single row. This group of cells has a defined start but a variable end. I tried doing this, but it didn't work. I'm still learning the Syntax of VBA but I haven't seen anything that says this WON'T work. Any help is appreciated.

我正在尝试沿一行连接一系列单元格。这组单元格具有定义的开始但可变的结束。我尝试这样做,但没有奏效。我仍在学习 VBA 的语法,但我还没有看到任何说这行不通的内容。任何帮助表示赞赏。

Dim hexVal As String

For i = 4 To N + 3
    Cells(3, i) = Application.WorksheetFunction.Dec2Hex(Cells(2, i), 2) & " "
Next i

hexVal = CONCATENATE(Range(Cells(3,i),Cells(3,N+3))

End Sub

回答by Alex

You do not need Concatenate(), but using &instead:

您不需要 Concatenate(),而是使用&代替:

for i = 4 to N + 3
  hexVal = hexVal & cells(3,i)
next i

That is in case you are just concatenate the strings and you do know the range needs to be concatenate.

以防万一您只是连接字符串并且您确实知道需要连接范围。

回答by David Zemens

HEre's your problem:

这是你的问题:

CONCATENATE(Range(Cells(3,i),Cells(3,N+3))

The Cellsmethod returns a range object, the default property of which is the .Valueproperty. So, this is equivalent to:

Cells方法返回一个范围对象,其默认属性是.Value属性。所以,这相当于:

CONCATENATE(Range(Cells(3,i).Value,Cells(3,N+3).Value)

As such, it will ALWAYS FAILunless those cells contain a valid address string.

因此,除非这些单元格包含有效的地址字符串,否则它将始终失败

Solution ...just use the built-in concatenator

解决方案......只需使用内置连接器

hexVal = Range(Cells(3,i) & Cells(3,N+3))

Or:

或者:

hexVal = CONCATENATE(Range(Cells(3,i).Value,Cells(3,N+3).Value))