使用宏来创建新函数LookUpConcat但它崩溃了

时间:2014-07-29 16:52:15

标签: excel vba excel-vba

我需要将来自单元格的文本连接到一个单元格中。我发现这个宏在前一段时间写过,这可能是我的问题,它在excel中创建了一个名为LookUpConcat的新函数。我第一次将它复制到我的VBA并创建公式=LookUpConcat($B$2,Usage!$AA$2:$AA$5000,$AG$2:$AG$5000," ")时,它看起来效果很好。然后它开始崩溃并给我#NAME错误,所以我开始新鲜。现在它说它在开头的每个=符号都有编译错误。 (String ="",Boolean = True,....)

Function LookUpConcat(ByVal SearchString As String, SearchRange As Range, ReturnRange As Range, _
                       Delimiter As String = " " , MatchWhole As Boolean = True, _
                       UniqueOnly As Boolean = False,  MatchCase As Boolean = False)

  Dim X As Long, CellVal As String, ReturnVal As String, Result As String

  If (SearchRange.Rows.Count > 1 And SearchRange.Columns.Count > 1) Or _
     (ReturnRange.Rows.Count > 1 And ReturnRange.Columns.Count > 1) Then
    LookUpConcat = CVErr(xlErrRef)
  Else
    If Not MatchCase Then SearchString = UCase(SearchString)
    For X = 1 To SearchRange.Count
      If MatchCase Then
        CellVal = SearchRange(X).Value
      Else
        CellVal = UCase(SearchRange(X).Value)
      End If
      ReturnVal = ReturnRange(X).Value
      If MatchWhole And CellVal = SearchString Then
        If UniqueOnly And InStr(Result & Delimiter, Delimiter & ReturnVal & Delimiter) > 0 Then     GoTo Continue
        Result = Result & Delimiter & ReturnVal
      ElseIf Not MatchWhole And CellVal Like "*" & SearchString & "*" Then
        If UniqueOnly And InStr(Result & Delimiter, Delimiter & ReturnVal & Delimiter) > 0 Then     GoTo Continue
        Result = Result & Delimiter & ReturnVal
      End If
Continue:
    Next

    LookUpConcat = Mid(Result, Len(Delimiter) + 1)

1 个答案:

答案 0 :(得分:0)

如果您没有向该变量的函数传递任何内容,那么您引用的那些等号将指定这些参数的默认值。 Excel不希望您在未明确声明这些参数为可选的情况下指定默认值。更改以下行:

Function LookUpConcat(ByVal SearchString As String, SearchRange As Range, ReturnRange As Range, _
                   Delimiter As String = " " , MatchWhole As Boolean = True, _
                   UniqueOnly As Boolean = False,  MatchCase As Boolean = False)

要:

Function LookUpConcat(ByVal SearchString As String, SearchRange As Range, ReturnRang As Range, _
                   Optional Delimiter As String = " ", Optional MatchWhole As Boolean = True, _
                   Optional UniqueOnly As Boolean = False, Optional MatchCase As Boolean = False)

在此代码之后,我可以假设您有End If后跟End Function吗?在这些更改之后,它会在我的机器上编译。