VBA - 从字符串中提取最后一个单词并从提取中创建新字符串

时间:2017-06-01 07:28:03

标签: excel vba excel-vba

我有这个选择客户的功能

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getActivity().getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
}

用户选择了BMW文件夹或丰田车 所以Function GetFolder() As String Dim fldr As FileDialog Set fldr = Application.FileDialog(msoFileDialogFolderPicker) With fldr .Title = "Select" .AllowMultiSelect = False If .Show = 0 Then MsgBox ("Canceled") Exit Function Else: sItem = .SelectedItems(1) GoTo NextCode End If End With NextCode: GetFolder = sItem Set fldr = Nothing End Function
sItem = "T:\DOCUMENTATION\BMW"

我需要从字符串(sItem = "T:\DOCUMENTATION\TOYOTA")中提取哪个客户(sItemBMW)并创建新的提取字符串Toyota

所以结果将是sItemCustomer

你能帮帮我吗?

3 个答案:

答案 0 :(得分:2)

SPLIT是您所需要的,或者更多的工作,INSTRINSTRREVMIDRIGHT

split(sItem,"\")(2)

正确地做"

Function pop(strInput As String, Optional strDelim As String = "\") As String
    Dim a() As String
    a = Split(strInput, strDelim)
    pop = a(UBound(a))
    Erase a
End Function

答案 1 :(得分:2)

如上所述 Nathan_Sav ,另一种方法是:

sItemCustomer = Right(sItem, Len(sItem) - InStrRev(sItem, "\"))

答案 2 :(得分:0)

这是从字符串中提取第n个单词的UDF。只需在第20,21,22行用您的角色替换空格 无需费力即可找到最后一个单词的公式也是-= ExtractWord(B2,LEN(B2)-LEN((SUBSTITUTE(B2,“”,“”))))) 或

= ExtractWord(“ STRing”,单词数)

Function ExtractWord(r As Range, WordCoice As Integer)
Dim CompanyName As String 
CompanyName = Trim(r.Value) 
CompanyNameLen = Len(CompanyName) 
CompanyNameWordCount = Len(Trim(CompanyName)) - Len(Replace(Trim(CompanyName), " ", "")) + 1 
If CompanyNameWordCount > 1 Then 
    Choice = WordCoice 
Else 
    ExtractWord = CompanyName 
    Exit Function 
End If 
If Choice > CompanyNameWordCount Or Choice < 1 Then 
    ExtractWord = "#N/A" 
    Exit Function 
Else
WordPos = 1
Count = 1
Do While Count <= Choice
Count = Count + 1
    If InStr(1, CompanyName, " ", vbTextCompare) > 0 Then
        ChosenWord = Mid(CompanyName, 1, InStr(1, CompanyName, " ", vbTextCompare) - 1)
        WordPos = InStr(1, CompanyName, " ", vbTextCompare) + 1 
        CompanyName = Mid(CompanyName, WordPos, CompanyNameLen) 
    Else
        ChosenWord = CompanyName
    End If 
Loop
ExtractWord = ChosenWord
End If
End Function