【问题标题】:Excel Macro to concatenate用于连接的 Excel 宏
【发布时间】:2011-01-30 17:03:58
【问题描述】:

在创建 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 列,因此我的连接函数将是 =连接(B1,C1,D1) 同样,我希望结果在 B1 中,但如果我必须隐藏,这不是问题。

谁能帮我做这件事?

【问题讨论】:

    标签: excel


    【解决方案1】:

    您可以使用以下 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
      

      【讨论】:

      • 如何从我的excel表格中调用函数?
      • 就像 AdamRalph 提到的那样。
      猜你喜欢
      • 2015-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-06
      • 1970-01-01
      • 2020-04-05
      • 2014-04-19
      相关资源
      最近更新 更多