excel - VBA Excel 2016 创建调用用户定义函数的宏
问题描述
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 不是很有经验。
任何意见,将不胜感激。
解决方案
一些建议:
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
推荐阅读
- javascript - Vue.js 挂载方法调用了两次
- java - 了解java类文件
- node.js - 状态从开始变为崩溃 - heroku
- java - GeckoDriver Selenium 问题:不下载任何东西如何解决?
- swift - 单击 Firebase 动态链接不会调用 AppDelegate 中的应用程序 (_: continue: restoreHandler :) 方法
- flutter - 在颤动中用 Mockito 模拟 3rd 方库的静态方法的最佳方法是什么
- class - Delphi AV 在自定义类中使用 TStringList
- python - 使用 python 和 json 保存和生成用户生成的数据
- android-studio - 无法使用 android studio 在模拟器上运行项目
- html - 固定的 CSS 位置不适用于 display flex