Hello I am trying to get part of my string out and was wondering if anyone can help so here is what I am working with
Dim tempName, NewName As String
'This is an example of what tempName will Equal
'What I need is the information in between the first -
'and the second one. In this case it would be 120
'I can not do it by number because the dashes are the only thing
'that stays the same.
tempName = "3-120-12-6"
NewName = tempName 'Do not know what String Manipulation to use.
Another few examples would be 6-56.5-12-12 I need the 56.5 or 2-89-12-4 I would need the 89
Thank you for the help.
You can do this too... You can break it up into pieces by detecting the first -. Then get the second...
Dim x as String = Mid(tempName, InStr(tempName, "-") + 1)
NewName = Mid(x, 1, InStr(x , "-") - 1)
Or make something like this to get it into 1 line of code...
NewName = Mid(Mid(tempName, InStr(tempName, "-") + 1), 1, InStr(Mid(tempName, InStr(tempName, "-") + 1), "-") - 1)
Or the quickest approach to this would be to use Split like the code below... This code equates the values between - into an array. Since you want the second value, you'd want the array with the index of 1 since an array starts with 0. If you're only starting, do try to create your own way to manipulate the string, this will help your mind think of new things and not just rely on built-in functions...
Dim tempName As String = "3-120-12-6"
Dim secondname() As String = Split(tempName, "-")
NewName = secondname(1)
Related
I have this String:
"[" & vbCrLf & " ""APPLE""" & vbCrLf & "]"
The only thing I need is APPLE.
I tried a few options with Split, Trim, Left and more, but they didn't work very well.
Thank you very much!
As the comments above have said, there's not enough information to give an answer without making assumptions, which could be wrong. I've assumed you want to extract the value between two quotation marks, regardless of what else is before or after.
If that's what you want, try this:
Dim Result As String = Nothing
Dim source As String = $"[{vbCrLf}""Apple""{vbCrLf}]"
Dim FirstQuote As Integer = source.IndexOf("""")
If FirstQuote > -1 And source.Length > FirstQuote Then
Dim SecondQuote As Integer = source.IndexOf("""", FirstQuote + 1)
If SecondQuote > FirstQuote Then
Result = source.Substring(FirstQuote + 1, SecondQuote - FirstQuote - 1)
End If
End If
If Result Is Nothing Then
'Handle Invalid Format
Else
'Process Result
End If
You would need to modify that so that you passed your source string, rather than defining it in the code. If you wanted to extract multiple words from a single string in the same format, just set FirstQuote = SecondQuote + 1, check that doesn't exceed the length of the source string and loop through again.
I am going to assume that you probably just need to get the first occurance of a string (in this case "apple") within square-brackets using split and so:
Dim AppleString As String = "This is an [Apple] or etc [...]"
console.WriteLine(AppleString.split("[")(1).split("]")(0).trim())
⚠️ This is not a solution for all purposes !!!
I am writing a macro to separate some data in one cell to multiple columns using the text to columns function. The problem I am running into is figuring out a way to separate a cell with multiple times in it, like so: "9:0011:008:0012:30".
I would like to separate it out into: "9:00" "11:00" etc. If I separate by ":" I'm going to get 9, 00, 11, 00. If I do it by ":**" I'm only going to get 9, 11, 8, 12, cutting off the 12:30 time.
Thanks in advance!
This is my golf attempt:
Option Explicit
Public Sub TestMe()
Dim strInput As String
Dim counter As Long
Dim strCurrent As String
strInput = "9:0011:008:0012:30"
For counter = 1 To Len(strInput) - 2
If Mid(strInput, counter, 1) = ":" Then
Debug.Print strCurrent & Mid(strInput, counter, 3)
counter = counter + 2
strCurrent = vbNullString
Else
strCurrent = strCurrent & Mid(strInput, counter, 1)
End If
Next counter
End Sub
It nicely returns:
9:00
11:00
8:00
12:30
It assumes that the minutes are always with two digits. You can easily change it to a function, returning Array().
The TextToColumns() function requires a Delimiter that is essentially "sacrificed", and you do not have one in those strings! Therefore, the TextToColumns() approach is not viable.
I suggest you use VBA string manipulation functions instead:
Find the position of the first ":" in the string; call it "p"
Extract your first item (the characters from the 1st to the p+2) into an output variable, call it x
Remove the x from the original string
Go to Step 1
I am trying to write a VBA code ; I have 3-days experience as vba programmer. So trying my best based on my pascal programming experience.
find number in hexadecimal string from excel, check the position of number if its odd then replace the number with new number. If its not odd then continue searching for other occurrence within the same string.
I have 15,000 hexa strings where I need to recursively search. range(B1:B15000)
Example:
Hexa string - Cell B1 - 53706167686574746920616c6c9261676c696f2c206f6c696f20652070657065726f63696e692537
translates to text - Spaghetti all�aglio, olio e peperocini
i want to replace 92(�) with 65(e) but in hexa string you notice there are multiple occurrences of 92 number but only one 92 falls at odd position to be replaced.
In excel I tried following:
=IF(ISODD(IF(ISERROR(SEARCH(92,B5)),0,SEARCH(92,B5)))=TRUE,SUBSTITUTE(B5,92,"27"),"no 92")
This works only for first occurrence in cell,
tried modifying it to search further but no luck:
=IF(ISODD(IF(ISERROR(SEARCH(92,B6)),0,SEARCH(92,B6)))=TRUE,SUBSTITUTE(B6,92,"27"),IF(ISODD(IF(ISERROR(SEARCH(92,B6,SEARCH(92,B6)+1)),0,SEARCH(92,B6,SEARCH(92,B6)+1)))=TRUE,SUBSTITUTE(B6,92,"27"),"no 92"))
Any suggestions are welcome.
How about a small UDF, looking only at every second position?
Function replaceWhenAtOddPos(ByVal s As String, findStr As String, replaceStr As String)
replaceWhenAtOddPos = s
If Len(findStr) <> 2 Or Len(replaceStr) <> 2 Then Exit Function
Dim i As Long
For i = 1 To Len(s) Step 2
If Mid(s, i, 2) = findStr Then s = Left(s, i - 1) & replaceStr & Mid(s, i + 2)
Next i
replaceWhenAtOddPos = s
End function
call:
replaceWhenAtOddPos("53706167686574746920616c6c9261676c696f2c206f6c696f20652070657065726f63696e692537", "92", "65")
Please put the following UDF in a standard module:
Public Function replace_hex(str As String, srch As Integer, repl As Integer) As String
Dim pos As Integer
pos = InStr(pos + 1, str, CStr(srch))
Do Until pos = 0
If pos Mod 2 = 0 Then str = Left(str, pos - 1) & CStr(repl) & Mid(str, pos + 2)
pos = InStr(pos + 1, str, CStr(srch))
Loop
replace_hex = str
End Function
and call it in your worksheet like that:
=replace_hex(A1,92,65)
I have a script that takes the contents of a cell, and puts the first 2 characters of the cell into a string array. I need to later compare that string array to a string, but I can't seem to get that to work. Here's what I have:
For i = 2 To 600
colStr = Sheets("smartlist").Cells(i, "A").Value
If colStr <> "" Then
ReDim charArray(Len(colStr) - 1)
For j = 1 To Len(colStr)
charArray(j - 1) = Mid$(colStr, j, 1)
Next
strArray = LCase(charArray(0)) & LCase(charArray(1))
If CStr(Join(strArray)) = CStr(Join(pwArray)) Then
Now, I've tried:
If charArray = "ab"
If Join(charArray) = "ab"
If CStr(Join(charArray)) = "ab"
I'm pretty lost at this point. Any suggestions would be welcome!
Edit: added the whole function up until I get the 'Type mismatch'
You could use Join(charArray, "") - without "" it joins the elements with space so the result of your initial try was "a b"
Firstly, you really need to clarify what you're doing. You say that later you need to check what's in the string. If that is the case, then you don't need an array, you simply need another string...
Dim chars As String
chars = Left$(cellToTest, 2)
Later you can test more simply using the InStr function, like so...
Dim loc As Integer
loc = Instr(colStr, chars)
If loc > 0 Then
...
If you want to turn this into a function on your spreadsheet you can use the following in the cells as formulas...
=LEFT(A1, 2)
=SEARCH(A3, A1)
Here's a little screen shot of what I mean...
I have a list of filenames in a spreadsheet in the form of "Smith, J. 010112.pdf". However, they're in the varying formats of "010112.pdf", "01.01.12.pdf", and "1.01.2012.pdf". How could I change these to one format of "010112.pdf"?
Personally I hate using VBA where worksheet functions will work, so I've worked out a way to do this with worksheet functions. Although you could cram this all into one cell, I've broken it out into a lot of independent steps in separate columns so you can see how it's working, step by step.
For simplicity I'm assuming your file name is in A1
B1 =LEN(A1)
determine the length of the filename
C1 =SUBSTITUTE(A1," ","")
replace spaces with nothing
D1 =LEN(C1)
see how long the string is if you replace spaces with nothing
E1 =B1-D1
determine how many spaces there are
F1 =SUBSTITUTE(A1," ",CHAR(8),E1)
replace the last space with a special character that can't occur in a file name
G1 =SEARCH(CHAR(8), F1)
find the special character. Now we know where the last space is
H1 =LEFT(A1,G1-1)
peel off everything before the last space
I1 =MID(A1,G1+1,255)
peel off everything after the last space
J1 =FIND(".",I1)
find the first dot
K1 =FIND(".",I1,J1+1)
find the second dot
L1 =FIND(".",I1,K1+1)
find the third dot
M1 =MID(I1,1,J1-1)
find the first number
N1 =MID(I1,J1+1,K1-J1-1)
find the second number
O1 =MID(I1,K1+1,L1-K1-1)
find the third number
P1 =TEXT(M1,"00")
pad the first number
Q1 =TEXT(N1,"00")
pad the second number
R1 =TEXT(O1,"00")
pad the third number
S1 =IF(ISERR(K1),M1,P1&Q1&R1)
put the numbers together
T1 =H1&" "&S1&".pdf"
put it all together
It's kind of a mess because Excel hasn't added a single new string manipulation function in over 20 years, so things that should be easy (like "find last space") require severe trickery.
Here's a screenshot of a simple four-step method based on Excel commands and formulas, as suggested in a comment to the answered post (with a few changes)...
This function below works. I've assumed that the date is in ddmmyy format, but adjust as appropriate if it's mmddyy -- I can't tell from your example.
Function FormatThis(str As String) As String
Dim strDate As String
Dim iDateStart As Long
Dim iDateEnd As Long
Dim temp As Variant
' Pick out the date part
iDateStart = GetFirstNumPosition(str, False)
iDateEnd = GetFirstNumPosition(str, True)
strDate = Mid(str, iDateStart, iDateEnd - iDateStart + 1)
If InStr(strDate, ".") <> 0 Then
' Deal with the dot delimiters in the date
temp = Split(strDate, ".")
strDate = Format(DateSerial( _
CInt(temp(2)), CInt(temp(1)), CInt(temp(0))), "ddmmyy")
Else
' No dot delimiters... assume date is already formatted as ddmmyy
' Do nothing
End If
' Piece it together
FormatThis = Left(str, iDateStart - 1) _
& strDate & Right(str, Len(str) - iDateEnd)
End Function
This uses the following helper function:
Function GetFirstNumPosition(str As String, startFromRight As Boolean) As Long
Dim i As Long
Dim startIndex As Long
Dim endIndex As Long
Dim indexStep As Integer
If startFromRight Then
startIndex = Len(str)
endIndex = 1
indexStep = -1
Else
startIndex = 1
endIndex = Len(str)
indexStep = 1
End If
For i = startIndex To endIndex Step indexStep
If Mid(str, i, 1) Like "[0-9]" Then
GetFirstNumPosition = i
Exit For
End If
Next i
End Function
To test:
Sub tester()
MsgBox FormatThis("Smith, J. 01.03.12.pdf")
MsgBox FormatThis("Smith, J. 010312.pdf")
MsgBox FormatThis("Smith, J. 1.03.12.pdf")
MsgBox FormatThis("Smith, J. 1.3.12.pdf")
End Sub
They all return "Smith, J. 010312.pdf".
You don't need VBA. Start by replacing the "."s with nothing:
=SUBSTITUTE(A1,".","")
This will change the ".PDF" to "PDF", so let's put that back:
=SUBSTITUTE(SUBSTITUTE(A1,".",""),"pdf",".pdf")
Got awk? Get the data into a text file, and
awk -F'.' '{ if(/[0-9]+\.[0-9]+\.[0-9]+/) printf("%s., %02d%02d%02d.pdf\n", $1, $2, $3, length($4) > 2 ? substr($4,3,2) : $4); else print $0; }' your_text_file
Assuming the data are exactly as what you described, e.g.,
Smith, J. 010112.pdf
Mit, H. 01.02.12.pdf
Excel, M. 8.1.1989.pdf
Lec, X. 06.28.2012.pdf
DISCLAIMER:
As #Jean-FrançoisCorbett has mentioned, this does not work for "Smith, J. 1.01.12.pdf". Instead of reworking this completely, I'd recommend his solution!
Option Explicit
Function ExtractNumerals(Original As String) As String
'Pass everything up to and including ".pdf", then concatenate the result of this function with ".pdf".
'This will not return the ".pdf" if passed, which is generally not my ideal solution, but it's a simpler form that still should get the job done.
'If you have varying extensions, then look at the code of the test sub as a guide for how to compensate for the truncation this function creates.
Dim i As Integer
Dim bFoundFirstNum As Boolean
For i = 1 To Len(Original)
If IsNumeric(Mid(Original, i, 1)) Then
bFoundFirstNum = True
ExtractNumerals = ExtractNumerals & Mid(Original, i, 1)
ElseIf Not bFoundFirstNum Then
ExtractNumerals = ExtractNumerals & Mid(Original, i, 1)
End If
Next i
End Function
I used this as a testcase, which does not correctly cover all your examples:
Sub test()
MsgBox ExtractNumerals("Smith, J. 010112.pdf") & ".pdf"
End Sub