如何将Excel公式转换为UDF?
我有一个公式来交换名称格式为“史密斯,约翰”的单元格中的姓氏。
=MID(A4&" "&A4,(FIND(" ",A4)+1),(LEN(A4)-1))
我创build了一个function来利用这个function,它似乎起初工作。 function是:
Function SwapNames(text As String) As String SwapNames = Mid(text & " " & text, (Find(" ", text) - 1, (Len(text) - 1)) End Function
我把我的工作簿转换成一个加载文件types,所以我可以全局使用它,现在它说Find函数是未定义的。 我在这里做错了什么?
正如@Nathan_Sav所说的 – 使用split,也许是一个可选的参数来标识分隔符。
所以=swapnames("Bartrup-Cook Darren")
返回“Darren Bartrup-Cook”和=swapnames("Bartrup-Cook Darren","-")
返回“Cook Darren Bartrup” #REF!
如果分隔符不在string中,则返回错误。
Function SwapNames(text As String, Optional Delimiter As String = " ") As Variant Dim SplitAt As Long Dim NamePart As Variant SplitAt = InStr(text, Delimiter) If SplitAt = 0 Then SwapNames = CVErr(xlErrRef) Else NamePart = Split(text, Delimiter) SwapNames = NamePart(1) & " " & NamePart(0) End If End Function
这是如何使用Split
function和交换名称。
Function SwapNames(text As String) As String SwapNames = Trim(Split(text, ",")(1)) & " " & Trim(Split(text, ",")(0)) End Function
所以它会改变Smith, John
, John Smith
, Smith, John J
, John J Smith
。