Not able to split for multiple special characters - excel

I am trying to split cell value up to last "\" in string
'C:\Users\punateng\Desktop\Pending Spec Updates.xlsx' in cell A1 so that result in cell B1 should be 'C:\Users\punateng\Desktop\'
I have written below code:
Sub mu()
Cells(1, 2).Value = Split(Cells(1, 1).Value, "\")
End Sub
But i am getting result as C: in cell B1.
Please help.

This is a case where a function is better than a sub.
Excel has Find and Search functions but doesn't have a FindLast function.
In a User Defined Function (UDF) you can use some functions that aren't available in the Application.WorksheetFunction collection. One of them is InstrRev which finds the position of the first instance of a string like "\" reading backwards from the end of the string. Using This little gem of knowledge and text editing functions you can build this UDF:
Function FileNameFromPath(Path1 As String)
'Test if you have been parsed an network file path
If InStr(1, Path1, "\") > 0 Then
'Get whatever is after the last "\"
FileNameFromPath = Right(Path1, Len(Path1) - InStrRev(Path1, "\"))
Else
'Could be a SharePoint file with http// address
If InStr(1, Path1, "\") > 0 Then
'Get whatever is after the last "/"
FileNameFromPath = Right(Path1, Len(Path1) - InStrRev(Path1, "/"))
Else
'There isn't a path separator there
FileNameFromPath = "That ain't a path"
End If
End If
End Function
So you can call this UDF in any cell in your workbook by typing "=fi", hitting Tab to paste it into your cell, then selecting the cell you want to test and enter a end bracket ")".

Split returns a string array, which in this case will consist of each part of the input text that was previously separated by a \ - so, you are actually returning the array {"C:";"Users";"punateng";"Desktop";"Pending Spec Updates.xlsx"}. When you try to paste this into Cells(1,2), VBA just interprets this as being the first element of the string array.
Instead, you might want to try
Cells(1,2).Value=Left(Cells(1,1).Value,InstrRev(Cells(1,1).Value,"\")-1)
which should find the last instance of \ and return the text before it.

Related

How to find the text between two values in a string?

I currently have a cell("Filename"). This returns H:\F0791\Purchase Requisitions\[PCS.xlsm].
I would like to single out the 'F0791' Value. I have previously used MID functions however, this does not work if 'F0791' is a different length.
Would it be possible to call up the values between the first two '\'s or is there a better alternative?
I am seeking this in both formula state and VBA. This is different to other questions because they do not offer a formula alternative.
You could use this UDF, that uses the Split Function
Function EXTRACTELEMENT(Txt As String, n, Separator As String) As String
On Error GoTo ErrHandler:
EXTRACTELEMENT = Split(Application.Trim(Mid(Txt, 2)), Separator)(n - 1)
Exit Function
ErrHandler:
' error handling code
MsgBox "ERROR: Verify if the data exists, example if the separator is correct."
On Error GoTo 0
End Function
And this is a test in VBA
Sub test()
Text = "H:\F0791\Purchase Requisitions[PCS.xlsm]"
Debug.Print EXTRACTELEMENT(CStr(Text), 2, "\")
End Sub
And you could also add it to a Cell, If E1= "H:\F0791\Purchase Requisitions[PCS.xlsm]" Then you add this to the desired result cell.
On cell F1, this formula:=EXTRACTELEMENT(E1;2;"\") gives the result on the image below:
Or open the insert function window
Optional, Description for UDF
This code adds a description for the UDF. You must run it once.
Sub DescribeFunction()
Dim FuncName As String
Dim FuncDesc As String
Dim Category As String
Dim ArgDesc(1 To 3) As String
FuncName = "EXTRACTELEMENT"
FuncDesc = "Returns the nth element of a string that uses a separator character"
Category = 7 'Text category
ArgDesc(1) = "String that contains the elements"
ArgDesc(2) = "Element number to return"
ArgDesc(3) = "Single-character element separator (spc default)"
Application.MacroOptions _
Macro:=FuncName, _
Description:=FuncDesc, _
Category:=Category, _
ArgumentDescriptions:=ArgDesc
End Sub
Another formula approach is to use this formula =MID(A1,4,FIND("----",SUBSTITUTE(A1,"\","----",2),1)-4) in cell B2 in case your strings are in column A
For a formula approach, the following worked for me, given that the "filename" cell is in A1:
=MID(A1,FIND("\",A1)+1,((FIND("\",A1,FIND("\",A1)+1))-(FIND("\",A1))-1))
This basically finds the position of the first "\" and the second "\" and uses the mid() function to pull the string between the two "\"s.
=MID(A2, FIND("\", A2)+1, FIND("\", A2, 4) - 4)
This worked for me assuming that the structure is more or less the same except with regard to the length of the code.

Find how many words from cell are found in an array

I have two columns with data. The first one has some terms and the other one contains single words.
what I have
I'm looking for a way to identify which words from each cell from the first column appear in the second, so the result should look something like this (I don't need the commas):
what I need
My question is somehow similar to Excel find cells from range where search value is within the cell but not exactly, because I need to identify which words are appearing in the second column and there can be more than one word.
I also tried =INDEX($D$2:$D$7;MATCH(1=1;INDEX(ISNUMBER(SEARCH($D$2:$D$7;A2));0);))
but it also returns only one word.
If you are willing to use VBA, then you can define a user defined function:
Public Function SearchForWords(strTerm As String, rngWords As Range) As String
Dim cstrDelimiter As String: cstrDelimiter = Chr(1) ' A rarely used character
strTerm = cstrDelimiter & Replace(strTerm, " ", cstrDelimiter) & cstrDelimiter ' replace any other possible delimiter here
SearchForWords = vbNullString
Dim varWords As Variant: varWords = rngWords.Value
Dim i As Long: For i = LBound(varWords, 1) To UBound(varWords, 1)
Dim j As Long: For j = LBound(varWords, 2) To UBound(varWords, 2)
If InStr(1, strTerm, cstrDelimiter & varWords(i, j) & cstrDelimiter) <> 0 Then
SearchForWords = SearchForWords & varWords(i, j) & ", "
End If
Next j
Next i
Dim iLeft As Long: iLeft = Len(SearchForWords) - 2
If 0 < iLeft Then
SearchForWords = Left(SearchForWords, Len(SearchForWords) - 2)
End If
End Function
And you can use it from the Excel table like this:
=SearchForWords(A2;$D$2:$D$7)
I have a partial solution:
=IF(1-ISERROR(SEARCH(" "&D2:D7&" "," "&A2&" ")),D2:D7&", ","")
This formula returns an array of the words contained in the cell (ranges are according to your picture). This array is sparse: it contains empty strings for each missing word. And it assumes that words are always separated by one space (this may be improved if necessary).
However, native Excel functions are not capable of concatenating an array, so I think the rest is not possible with native formulas only.
You would need VBA but if you use VBA you should not bother with the first part at all, since you can do anything.
You can create a table with the words you want to find across the top and use a formula populate the cells below each word if it's found. See screenshot.
[edit] I've noticed that it's incorrectly picking up "board" in "blackboard" but that should be easily fixed.
=IFERROR(IF(FIND(C$1,$A2,1)>0,C$1 & ", "),"")
Simply concatinate the results
=CONCATENATE(C2,D2,E2,F2,G2,H2)
or
=LEFT(CONCATENATE(C2,D2,E2,F2,G2,H2),LEN(CONCATENATE(C2,D2,E2,F2,G2,H2))-2)
to take off the last comma and space
I've edited this to fix the problem with "blackboard"
new formula for C2
=IF(OR(C$1=$A2,ISNUMBER(SEARCH(" "&C$1&" ",$A2,1)),C$1 & " "=LEFT($A2,LEN(C$1)+1)," " & C$1=RIGHT($A2,LEN(C$1)+1)),C$1 & ", ","")
New formula for B2 to catch the error if there are no words
=IFERROR(LEFT(CONCATENATE(C2,D2,E2,F2,G2,H2,I2),LEN(CONCATENATE(C2,D2,E2,F2,G2,H2,I2))-2),"")

How to delete a string in an excel cell by comparing the value in another cell of the same excel

Scenario I tried:
This is the look and feel of my macro project
From the above image , Range (F4) string value is "GREEN" then i do not want to see Action for next week in range Range (G4) for this i used the below script , But it went in vain as I am not able to see the character getting deleted.
If ThisWorkbook.Sheets("FortnightlyWSR").Cells(I, 6).Value = "GREEN" Then
ThisWorkbook.Sheets("FortnightlyWSR").Range("G4").Characters(WorksheetFunction.Find("Action Plan for next Week:", ThisWorkbook.Sheets("FortnightlyWSR").Range("G4").Value, 1), Len("Action Plan for next Week:")).Delete
I don't think there was a lot wrong with your code but certainly the call to the WorksheetFunction object's FIND function could be replaced with VBA's native InStr function. A couple of vars to hold the string and the starting position simplify matters. A With ... End With statement takes the parent worksheet reference out to a single localized position.
Dim sp As Long, ln As Long, i As Long, str As String
i = 4
str = "Action Plan for next Week:" & Chr(10)
With ThisWorkbook.Sheets("FortnightlyWSR")
If UCase(.Cells(i, 6).Value2) = "GREEN" Then
sp = InStr(1, .Range("G4").Value, str, vbTextCompare)
.Range("G4").Characters(Start:=sp, Length:=Len(str)).Delete
End If
End With
I've added a line feed character onto the tail end of the string so that you wouldn't be left with a blank line.
The FIND function performs a case-senstive search; the SEARCH function's substring location is not case sensitive.
The code which you have posted will delete the string "Action Plan for next Week:" alone from the G4 cell and retains the remaining string.
Tested code - substituted I as 4 to match F4
If ThisWorkbook.Sheets("FortnightlyWSR").Cells(I, 6).Value = "GREEN" Then
ThisWorkbook.Sheets("FortnightlyWSR").Range("G4").Characters(WorksheetFunction.Find("Action Plan for next Week:", ThisWorkbook.Sheets("FortnightlyWSR").Range("G4").Value, 1), Len("Action Plan for next Week:")).Delete
End If
but if you want to remove whatever values below it has (from the image Print Solution.. , Test strategy .. Enablement test scenario .. ) then you can use the below code
I = 4
If ThisWorkbook.Sheets("FortnightlyWSR").Cells(I, 6).Value = "GREEN" Then
ThisWorkbook.Sheets("FortnightlyWSR").Range("G4").Characters(WorksheetFunction.Find("Action Plan for next Week:", ThisWorkbook.Sheets("FortnightlyWSR").Range("G4").Value, 1)).Delete
End If

Excel: Get Last characters from parent folder to sub folder

Need your help very badly. I need to get last characters from Folder Name and Sub Folder(if any). To make my point clearly I am giving an example below.
Eg 1:
E:\User\Images\Main_Folder_**1**\SubFolder**1**\Sub_Folder**2**\SubFolder**3**\SubFolder**4**\file.txt
Need to get string "11234".
Eg2:
E:\User\Images\Main_Folder_**1**\SubFolder**2**\Sub_Folder**5**\SubFolder**6**\SubFolder**9**\file.txt
Need to get string "12569".
I Have tried below code to get last character.
=FIND("#",SUBSTITUTE(A1,"\","#",(LEN(A1)-LEN(SUBSTITUTE(A1,"\","")))/LEN("\")))
But I need to search in sub folders(if any) too.
Really appreciate if you guys can provide any help. Thanks.
If your source data is as you show it; always starting with E:\User\Images, and IF that last character will always be a single digit, and IF there will always be 5 folders/subfolders, you could try:
=SUMPRODUCT(--RIGHT(TRIM(MID(SUBSTITUTE(SUBSTITUTE(A1,"E:\User\Images\",""),"\",REPT(" ",99)),(ROW(INDIRECT("1:5"))-1)*99+1,99)),1)*10^{4;3;2;1;0})
Otherwise I would suggest this User Defined Function:
Option Explicit
Function GetLastFolderChar(S As String) As String
Dim T() As String, U As String
Dim I As Long
S = Replace(S, "E:\User\Images\", "")
T = Split(S, "\")
For I = LBound(T) To UBound(T) - 1
U = U & Right(T(I), 1)
Next I
GetLastFolderChar = U
End Function
Possible solution to you problem is to create UDF VBA as shown below:
1). Add Module to you Excel Workbook (Module1 by default) and place a User Defined Function (UDF) in that module:
Option Explicit
Public Function GetLastChars(InputText As Range) As String
Dim tmp As String, ret As String
'skip E:\User\Images\ as per your example
tmp = Replace(InputText.Value, "E:\User\Images\", "")
'loop through the rest of subfolders
Do While (InStr(tmp, "\")) > 0
'adding the last letters to return var
ret = ret & Mid(tmp, InStr(tmp, "\") - 1, 1)
'progressing to the next subfolder
tmp = Mid(tmp, InStr(tmp, "\") + 1)
Loop
'concatenated last letters of subfolders
GetLastChars = ret
End Function
2) Assuming that as per you example the original data (path) is inserted in Cell "A1", enter in Cell "B1" the formula =GetLastChars(A1); correspondingly, in Cell "B2" enter the Formula: =GetLastChars(B1)
Corresponding to your sample: E:\User\Images\Main_Folder_1\SubFolder1\Sub_Folder2\SubFolder3\SubFolder4\file.txt the return value is 11234.
This UDF will work on any number of sub-folders (skipping the root part E:\User\Images as per your sample).
For example: having the path entered as E:\User\Images\Main_Folder_1\SubFolder1\Sub_Folder2\SubFolder3\SubFolder4\SubFolder5\SubFolder6\SubFolder7\file.txt the formula returns 11234567.
For path string like: E:\User\Images\Main_Folder_1\SubFolder1\Sub_Folder2\SubFolder3\SubFolder4\SubFolder5\SubFolder6\SubFolder7\SubFolder8\SubFolder9\SubFolder0\file.txt it returns 11234567890, and so on.
Hope this will help. Best regards,

Text Format Macro for Excel

I'm trying to convert a list of names, each in a seperate cell, into a list with # before each name commas afterwards and combined into a single cell. What type of macro would I use for that. So:
Help
Me
Please
Thank
You
into (single cell):
#help, #me, #please, #thank, #you
Thanks
Try this code:
function convertNames(startRow as long,endRow as long,column as long) as string
dim result as string
for c=startRow to endRow
result=result & "#" & Cells(c,column) & ", "
next
result=left(result,len(result)-2)
convertNames=result
end function
You would call this function in the cell where you want to display the results as:
=convertNames(5,12,2)
substituting in the start row, end row, and column index that you need.
Try this function:
Function ConvertNames(List As Range) As String
Dim C As Range
For Each C In List
ConvertNames = ConvertNames & "#" & C.Value2 & ", "
Next C
ConvertNames = Left(ConvertNames, Len(ConvertNames) - 2)
End Function
It is inspired by sigil's answer, but this one works with a range, and allows Excel to manage the references to cells. Sigil's function should be volatile and would slow down large files.
You need to add a module to the project and put this function in the module. Then you can use it by typing =ConvertNames(A1:A5) on the cell that uses it.

Resources