我正在尝试连接Excel中的一堆列。我知道我可以手动执行:
=A1&", "&B1&", "&C1
(依此类推)
但我有大约40个专栏,我正在寻找一种简化这一过程的方法。
提前感谢您的帮助!
答案 0 :(得分:3)
作为使用range
Public Function ClarkeyCat(ByRef rng As Range) As Variant
Dim c As Range
Dim ans As Variant
For Each c In rng
If (c.Value <> "") Then
ans = IIf(ans = "", "", ans & ",") & c.Value
End If
Next
ClarkeyCat = ans
End Function
如果需要,可以更改Variant
类型(最有可能改为string
)。
像这样使用:
答案 1 :(得分:2)
我会为此使用vba。对于每个列,您需要类似的东西(假设值在第1行中)
myString = ""
for i = 1 to 40
if i <> 40 then
myString = myString & Cells(1, i) & ", "
else:
myString = myString & Cells(1, i)
end if
next i
然后,myString将包含您的连接字符串的内容。
答案 2 :(得分:2)
让我发布我的功能。我过去也遇到过这个问题 当我尝试连接日期,错误和空白单元格时,通常会出现我的问题 因此,我尝试使用以下内容覆盖大部分内容:
Function CONCATPLUS(ref_value As Range, Optional delimiter As Variant) As String
Dim cel As Range
Dim refFormat As String, myvalue As String
If ref_value.Cells.Count = 1 Then CONCATPLUS = CVErr(xlErrNA): Exit Function
If IsMissing(delimiter) Then delimiter = " "
For Each cel In ref_value
refFormat = cel.NumberFormat
Select Case TypeName(cel.Value)
Case "Empty": myvalue = vbNullString
Case "Date": myvalue = Format(cel, refFormat)
Case "Double"
Select Case True
Case refFormat = "General": myvalue = cel
Case InStr(refFormat, "?/?") > 0: myvalue = cel.Text
Case Else: myvalue = Format(cel, refFormat)
End Select
Case "Error"
Select Case True
Case cel = CVErr(xlErrDiv0): myvalue = "#DIV/0!"
Case cel = CVErr(xlErrNA): myvalue = "#N/A"
Case cel = CVErr(xlErrName): myvalue = "#NAME?"
Case cel = CVErr(xlErrNull): myvalue = "#NULL!"
Case cel = CVErr(xlErrNum): myvalue = "#NUM!"
Case cel = CVErr(xlErrRef): myvalue = "#REF!"
Case cel = CVErr(xlErrValue): myvalue = "#VALUE!"
Case Else: myvalue = "#Error"
End Select
Case "Currency": myvalue = cel.Text
Case Else: myvalue = cel
End Select
If Len(myvalue) <> 0 Then
If CONCATPLUS = "" Then
CONCATPLUS = myvalue
Else
CONCATPLUS = CONCATPLUS & delimiter & myvalue
End If
End If
Next
End Function
截至目前,我还没有遇到过这个函数无法连接的单元格条目 随意根据您的需求或心灵内容进行调整。 HTH。
答案 3 :(得分:1)
连接范围单行或列时,您可以使用Application.Transpose
一次性完成此操作以避免范围循环
这个UDF有三个参数
,
)TRUE
- 进一步认为我将更新UDF以自动检测范围是row
还是{{1基于)请注意,就其他答案而言
column
评估IIF
和TRUE
参数,因为FALSE
没有[短路](
http://en.wikipedia.org/wiki/Short-circuit_evaluation)。所以VBA
内部循环可能很昂贵码
IFF
在下面的例子中
Function ConCat(rng1 As Range, Optional StrDelim As String, Optional bRow As Boolean) As String
Dim x
If StrDelim = vbNullString Then StrDelim = ","
x = Application.Transpose(rng1)
If bRow Then x = Application.Transpose(x)
ConCat = Join(x, StrDelim)
End Function
)为D1
=concat(A1:C1,",",TRUE)
中的公式为E1
答案 4 :(得分:0)
您始终可以使用Visual Basic For Applications(VBA)。它是Office的微软语言。以下是您可能正在寻找的示例,但请尝试使用Google计算机了解有关VBA以及如何将此代码输入电子表格的详情。
Sub ConcatColumns()
Do While ActiveCell <> "" 'Loops until the active cell is blank.
'The "&" must have a space on both sides or it will be
'treated as a variable type of long integer.
ActiveCell.Offset(0, 1).FormulaR1C1 = _
ActiveCell.Offset(0, -1) & " " & ActiveCell.Offset(0, 0)
ActiveCell.Offset(1, 0).Select
Loop
End Sub