【问题标题】:VBA Excel 2016 Creating a macro that calls a user defined functionVBA Excel 2016 创建调用用户定义函数的宏
【发布时间】:2021-08-30 21:26:45
【问题描述】:

Excel 2016 我使用用户定义的函数来组合一长串数字并用逗号分隔它们。使用我们的一些旧软件可以节省大量时间。我一直在使用的功能在这里。

Function ConcatDelim(ConcatRange As Variant) As String

    Dim Test As Boolean
    Test = True
    
    For Each i In ConcatRange
        If Test Then
            ConcatDelim = i
            Test = False
        Else
            ConcatDelim = ConcatDelim & ", " & i
        End If
    Next i
    
End Function

我想创建一个宏,在当前选定的单元格上使用此函数,在工作表顶部创建一个新行并将结果输出到 A1 中。

这是我为宏编写的内容。

Sub ConcatDelimMacro()
    ' Keyboard Shortcut: Ctrl+Shift+G
    'Concat Delim Function
    Dim SelectionRange As Range
    Dim varCellCount As Integer
    Dim ConcatString As String
    Set SelectionRange = Selection
    Set varCellCount = Count(SelectionRange)
    If varCellCount > 99 Then
        MsgBox "You have selected too many cells, please select 99 or fewer at a time"
    ElseIf varCellCount <= 99 Then
        Worksheets.Rows(1).Insert
        Concat = ConcatDelim(SelectionRange)
        Range(A1) = Concat
End Sub

我要么没有结果,要么编译错误“未定义子或函数”。我试过让函数和宏是同一个模块并且是分开的。很抱歉,我对 VBA 不是很有经验。

任何建议将不胜感激。

【问题讨论】:

  • varCellCount =SelectionRange.Cells.Count 没有 Set 因为它只用于对象类型变量
  • 你见过VBA中的Join函数吗?

标签: excel vba excel-2016


【解决方案1】:

一些建议:

Function ConcatDelim(ConcatRange As Variant) As String
    Dim sep As String, c As Range, v
    For Each c In ConcatRange.Cells
        v = Trim(c.Value)     'remove any extra spaces
        If Len(v) > 0 Then
            ConcatDelim = ConcatDelim & sep & v
            sep = ","         'add delimiter after first non-blank value
        End If
    Next c
End Function


Sub ConcatDelimMacro()
    Dim ConcatString As String
    
    If TypeName(Selection) <> "Range" Then
        MsgBox "Please first select up to 99 cells"
        Exit Sub
    End If
    
    If Selection.Cells.Count > 99 Then
        MsgBox "You have selected too many cells, please select 99 or fewer at a time"
    Else
        ConcatString = ConcatDelim(Selection)
        With Selection.Parent 'parent = the worksheet where range is selected
            .Rows(1).Insert
            .Range("A1").Value = ConcatString
        End With
    End If
End Sub

【讨论】:

  • 非常感谢,效果很好。
猜你喜欢
  • 1970-01-01
  • 2015-08-12
  • 2014-08-07
  • 2019-01-08
  • 1970-01-01
  • 2018-09-16
  • 1970-01-01
  • 1970-01-01
  • 2011-02-06
相关资源
最近更新 更多