连接函数更改

时间:2015-12-24 08:58:58

标签: excel excel-vba vba

单个条目的结果必须是 [CAR]而非0。

CAR是单次入场的例子。单次进入我总是得0。 有多个我得到[CAR; BIKE] 我需要改变什么才能获得[CAR] 代码:

Function ConcRange(ByRef myRange As Range, Optional ByVal Seperator As String = ";", Optional ByVal Begin As String = "[")
Conc = vbNullString
Dim rngCell As Range
For Each rngCell In myRange
If Conc = vbNullString Then
If Not rngCell.Value = vbNullString Then
Conc = CStr(rngCell.Value)
End If
Else
If Not rngCell.Value = vbNullString Then
Conc = Conc & Seperator & CStr(rngCell.Value)
ConcRange = "[" & Conc & "]"
End If
End If
Next rngCell
End Function

3 个答案:

答案 0 :(得分:1)

数组方法比范围循环快得多

此外,在连接字符串时,最小化对长字符串的调用,即

=ShortStr & (LongStr and ShortStr2)
比下面加入长字符串两次的方法更好

=ShortStr & LongStr and ShortStr2

Function ConcRange(ByRef myRange As Range, Optional ByVal Separator As String = ";") As String
Dim lngRow As Long
Dim lngCol As Long
Dim X

If myRange.Cells.Count > 1 Then
    X = myRange.Value2
    For lngRow = 1 To UBound(X, 1)
      For lngCol = 1 To UBound(X, 2)
        If Len(X(lngRow, lngCol)) > 0 Then
            If Len(ConcRange) > 0 Then
                ConcRange = ConcRange & (Separator & X(lngRow, lngCol))
            Else
                ConcRange = X(lngRow, lngCol)
            End If
      Next lngCol
    Next lngRow
Else
    If Len(myRange.Value2) > 0 Then ConcRange = myRange.Value2
End If

End Function

答案 1 :(得分:0)

这可能会做你想要的:

Function ConcRange(ByRef myRange As Range, Optional ByVal Seperator As String = ";", Optional ByVal Begin As String = "[") As String
    If (myRange.Rows.Count * myRange.Columns.Count = 1) Then
        ConcRange = "[" & myRange.Cells(1,1).Value & "]"
    End If
    Conc = vbNullString
    Dim rngCell As Range
    For Each rngCell In myRange
    If Conc = vbNullString Then
        If Not rngCell.Value = vbNullString Then
        Conc = CStr(rngCell.Value)
        End If
    Else
        If Not rngCell.Value = vbNullString Then
        Conc = Conc & Seperator & CStr(rngCell.Value)
        ConcRange = "[" & Conc & "]"
        End If
    End If
    Next rngCell
End Function

*免责声明:我目前无法访问Excel进行测试。

答案 2 :(得分:0)

使用当前代码,只有达到ELSE时,函数才会获得返回值。只有当myRange中有多个单元格时才会这样。

但它应该每次都获得一个返回值:

Function ConcRange(ByRef myRange As Range, Optional ByVal Seperator As String = ";") As String
 Dim Conc As String
 Conc = vbNullString
 Dim rngCell As Range
 For Each rngCell In myRange
  If Conc = vbNullString Then
   If Not rngCell.Value = vbNullString Then
    Conc = CStr(rngCell.Value)
   End If
  Else
   If Not rngCell.Value = vbNullString Then
    Conc = Conc & Seperator & CStr(rngCell.Value)
   End If
  End If
 Next rngCell
 ConcRange = "[" & Conc & "]"
End Function

提示:缩进代码有助于更好地理解依赖关系。