2010-03-23 88 views
3

需要幫助創建Excel宏。我有一個Excel工作表。Excel工作表不一致。 我打算使它統一和結構化。Excel宏連接

例如,

A   B   C   D 
1 test  tester   tester 
2 hai  test 
3 Bye  test   tested 
4 GN  test   tested Fine 

    A   B   C   D 
1 test  testertester 
2 hai  test 
3 Bye  testtested  
4 GN  testtestedFine 

基本上,我必須要找到其中元素放置成基於這樣我可以寫我的CONCATENATE功能可按最後一個單元格。

在這種情況下,將列d,因此我的串連函數本來 = CONCATENATE(B1,C1,D1) 再次我想的結果是在B1,但不是一個問題,如果我要躲。

任何人都可以幫助我做到這一點?

回答

4

您可以使用以下VBA函數,它可以連接(連接)來自任意範圍單元格的值,並帶有可選的分隔符。

Public Function Join(source As Range, Optional delimiter As String) 
    Dim text As String 
    Dim cell As Range: For Each cell In source.Cells 
     If cell.Value = "" Then GoTo nextCell 

     text = text & cell.Value & delimiter 

nextCell: 
    Next cell 

    If text <> "" And delimiter <> "" Then 
     text = Mid(text, 1, Len(text) - Len(delimiter)) 
    End If 

    Join = text 
End Function 

有關如何使用該函數,輸入= JOIN的一個示例:在任何地方(A1 D1)插入細胞在電子表格上。

2

= B1 & C1 & D1

,我已優化的亞當的功能。

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 
+0

如何從我的Excel表中調用函數? – Harish 2010-03-25 12:17:55

+0

就像AdamRalph提到的一樣。 – AMissico 2010-03-25 15:40:10