VBA 用于从单个单元格中提取多个值并将它们index/matching 转换为值的函数
VBA function for pulling multiple values from single cell and index/matching them to values
我在使用用户定义的函数将单个单元格字符串分解为多个值时遇到问题,然后以 index/match 方式匹配每个值,返回单个单元格和匹配的字符串以逗号分隔的值。
示例:
Roles Names Role Name
role1/role2 name1,name2 role1 name1
role1 name1 role2 name2
role2/role3 name2,name3 role3 name3
role1/role4 name1,name4 role4 name4
role3/role5 name3,name5 role5 name5
我想获得一个函数,从角色、角色和名称列生成 "names" 列。
到目前为止,这是我的 VBA 代码:
Public Function RoleToName(role, roles_rng, names_rng) As String
Dim result As String
Dim s As Variant
For Each s In Split(role, "/")
???
Next s
End Function
谢谢。
Public Function RoleToName(role, roles_rng, names_rng) As String
Dim result As String
Dim s As Variant, m, sep As String
For Each s In Split(role, "/")
'Trim each value in case of extra spaces...
m = Application.Match(Trim(s), roles_rng, 0)
If Not IsError(m) Then
result = result & sep & names_rng.Cells(m).Value
Else
result = result & sep & "??" '<< role not found...
End If
sep = ","
Next s
RoleToName = result
End Function
尝试一下,
Function udf_CollateNames(roles As String, tbl As Range, _
Optional roleSplit As String = "/", _
Optional delim As String = ",")
Dim v As Long, vVALs As Variant
vVALs = Split(roles, roleSplit)
For v = LBound(vVALs) To UBound(vVALs)
If Not IsError(Application.Match(Trim(vVALs(v)), tbl.Columns(1), 0)) Then _
udf_CollateNames = udf_CollateNames & delim & Application.VLookup(Trim(vVALs(v)), tbl, 2, False)
Next v
udf_CollateNames = Mid(udf_CollateNames, Len(delim) + 1)
End Function
我在使用用户定义的函数将单个单元格字符串分解为多个值时遇到问题,然后以 index/match 方式匹配每个值,返回单个单元格和匹配的字符串以逗号分隔的值。
示例:
Roles Names Role Name
role1/role2 name1,name2 role1 name1
role1 name1 role2 name2
role2/role3 name2,name3 role3 name3
role1/role4 name1,name4 role4 name4
role3/role5 name3,name5 role5 name5
我想获得一个函数,从角色、角色和名称列生成 "names" 列。
到目前为止,这是我的 VBA 代码:
Public Function RoleToName(role, roles_rng, names_rng) As String
Dim result As String
Dim s As Variant
For Each s In Split(role, "/")
???
Next s
End Function
谢谢。
Public Function RoleToName(role, roles_rng, names_rng) As String
Dim result As String
Dim s As Variant, m, sep As String
For Each s In Split(role, "/")
'Trim each value in case of extra spaces...
m = Application.Match(Trim(s), roles_rng, 0)
If Not IsError(m) Then
result = result & sep & names_rng.Cells(m).Value
Else
result = result & sep & "??" '<< role not found...
End If
sep = ","
Next s
RoleToName = result
End Function
尝试一下,
Function udf_CollateNames(roles As String, tbl As Range, _
Optional roleSplit As String = "/", _
Optional delim As String = ",")
Dim v As Long, vVALs As Variant
vVALs = Split(roles, roleSplit)
For v = LBound(vVALs) To UBound(vVALs)
If Not IsError(Application.Match(Trim(vVALs(v)), tbl.Columns(1), 0)) Then _
udf_CollateNames = udf_CollateNames & delim & Application.VLookup(Trim(vVALs(v)), tbl, 2, False)
Next v
udf_CollateNames = Mid(udf_CollateNames, Len(delim) + 1)
End Function