[英]How to turn an Excel formula into a UDF?
I have a formula to swap last names with first names in cells where the format is "Smith, John". 我有一个公式,可以在格式为“ Smith,John”的单元格中将姓氏与名字互换。
=MID(A4&" "&A4,(FIND(" ",A4)+1),(LEN(A4)-1))
I created a function to utilize this functionality and it seemed to work at first. 我创建了一个函数来利用此功能,并且起初似乎很有效。 The function is:
该函数是:
Function SwapNames(text As String) As String SwapNames = Mid(text & " " & text, (Find(" ", text) - 1, (Len(text) - 1)) End Function
I converted my workbook to an Add-In filetype so I could use this globally and now it says the Find function is undefined. 我将工作簿转换为加载项文件类型,因此可以全局使用它,现在它说Find函数未定义。 What am I doing wrong here?
我在这里做错了什么?
As @Nathan_Sav said - use split, and perhaps an optional argument to identify the delimiter. 就像@Nathan_Sav所说的-使用split,也许是一个可选参数来标识定界符。
So =swapnames("Bartrup-Cook Darren")
returns "Darren Bartrup-Cook" and =swapnames("Bartrup-Cook Darren","-")
returns "Cook Darren Bartrup" a #REF!
因此,
=swapnames("Bartrup-Cook Darren")
返回“ Darren Bartrup-Cook”,而=swapnames("Bartrup-Cook Darren","-")
返回“ Cook Darren Bartrup” #REF!
error is returned if the delimiter isn't present in the 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
This is how you can use Split
function and swap the name. 这是您可以使用
Split
功能和交换名称的方法。
Function SwapNames(text As String) As String
SwapNames = Trim(Split(text, ",")(1)) & " " & Trim(Split(text, ",")(0))
End Function
So it will change Smith, John
to John Smith
and Smith, John J
to John J Smith
. 因此它将把
Smith, John
更改为John Smith
和Smith, John J
更改为John J Smith
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.