2011-08-29 88 views
0

我發現這個定義Excel功能:添加分隔符來拼接列表

Function Join(source As Range, Optional delimiter As String) As String 
' 
' Join Macro 
' Joins (concatenates) the values from an arbitrary range of cells, 
' with an optional delimiter. 
' 

'optimized for strings 
' check len is faster than checking for "" 
' string Mid$ is faster than variant Mid 
' nested ifs allows for short-circuit + is faster than & 

    Dim sResult As String 
    Dim oCell As Range 

    For Each oCell In source.Cells 
     If Len(oCell.Value) > 0 Then 
      sResult = sResult + CStr(oCell.Value) + delimiter 
     End If 
    Next 

    If Len(sResult) > 0 Then 
     If Len(delimiter) > 0 Then 
      sResult = Mid$(sResult, 1, Len(sResult) - Len(delimiter)) 
     End If 
    End If 

    Join = sResult 
End Function 

我想調整它顯示的每個單元之間的逗號它結合創建列表。

+1

我不會名稱功能‘加入’,因爲已經有一個VBA函數與該名稱,那陣列上做同樣的工作(但不在範圍上)。 –

+0

我會第二! – aevanko

回答

5

看起來它已經通過可選的delimiter參數執行此操作。

就這樣稱呼它:

=JOIN(A1:A100,",") 
8

有幾件事情錯UDF你發現:

  • 級聯應以 「&」 而不是 「+」 來完成。
  • 使用範圍中的單元格比變體數組更慢,並且純粹從VBA內部工作。每次對Excel的調用都會產生一個小小的性能上的提升。
  • 如果連接正確完成,則轉換爲字符串是不理智的。
  • 應該優化連接,以便首先連接較小的部分,然後將結果添加到結果中,否則會將結果複製兩次以完成每個連接。
  • 名稱不應該加入,因爲VBA具有該名稱的功能。
  • 應該不需要檢查分隔符的LEN,因爲它是一個字符串。默認情況下,如果不存在,它將爲LEN(0),您可以毫無顧慮地從len(result)中減去0。
  • 不是什麼大不了的事情,但檢查不平等<>比稍微快一點。

這是我的版本。默認情況下,將單獨由每個單元「」如果你離開的第二個參數爲空(EX = ConcatenateRange(A1:A100)

Function ConcatenateRange(ByVal cell_range As range, _ 
        Optional ByVal seperator As String = ", ") As String 

Dim cell As range 
Dim newString As String 
Dim vArray As Variant 
Dim i As Long, j As Long 

vArray = cell_range.Value 

For i = 1 To UBound(vArray, 1) 
    For j = 1 To UBound(vArray, 2) 
     If Len(vArray(i, j)) <> 0 Then 
      newString = newString & (seperator & vArray(i, j)) 
     End If 
    Next 
Next 

If Len(newString) <> 0 Then 
    newString = Right$(newString, (Len(newString) - Len(seperator))) 
End If 

ConcatenateRange = newString 

End Function 
+0

+1尼斯分析。 –

+0

@Issun這將更快:**右$(newString,(Len( newString) - Len(seperator)))**或類似的東西:** Mid $(newString,Len(分隔符)+1)**?我使用後者,因爲代碼更短,但我從未檢查過速度 –

+0

當前計算機上的差異可能可以忽略不計,但Right()比Mid()快。 – aevanko