I'm still learning how to make scripts in VBA.
For now I want to create script converting text from cell to Unicode Little Endian Hex. I have script that works now only for first character. How should i apply loop to switch to next letter, add it to print and finish script when text is over?
Function Text2LE(Character As String)
Dim x As Long
x = AscW(Character)
If x < 16 Then
Text2LE = "000" & Hex(AscW(Character))
Text2LE = Right(Text2LE, 2) & Left(Text2LE, 2)
ElseIf x < 256 Then
Text2LE = "00" & Hex(AscW(Character))
Text2LE = Right(Text2LE, 2) & Left(Text2LE, 2)
Else
Text2LE = "0" & Hex(AscW(Character))
Text2LE = Right(Text2LE, 2) & Left(Text2LE, 2)
End If
End Function
you need something like to loop through the Character in the string and convert it using your function! Then Group the HEX together and display or consume! (Not to sure on the display of hex in debug window)
sub Convert()
Dim i as long
Dim string_to_convert as string
Dim Hex as String
For i = 1 to len(string_to_convert)
Hex = Hex + Text2LE(Mid(string_to_convert, i, 1))
Next i
debug.Print Hex
end sub
Related
This question already has answers here:
Add leading zeroes/0's to existing Excel values to certain length
(8 answers)
Closed 3 years ago.
I have values of 120, 136, 7120, 72136. The maximum string length should be 5, how do I go about making 120 "00120" and 136 "00136" etc?
Single line will work
VBA
Range("A1").Value = "'" & Format(Range("A1").Value, "00000")
Excel
=TEXT(A1,"00000")
In your simple case you can try something simple like this:
Sub FiveCharString()
Dim myStr As String
myStr = "136"
If Len(myStr) = 2 Then
myStr = "000" & myStr
ElseIf Len(myStr) = 3 Then
myStr = "00" & myStr
ElseIf Len(myStr) = 4 Then
myStr = "0" & myStr
End If
Debug.Print myStr
End Sub
Returns 00136.
Function FillWithZero(number as long, digitCount as long) as string
FillWithZero = Right(String(digitCount , "0") & number , digitCount)
End Function
Use a custom number format in your cells.
See Using a custom number format to display leading zeros
or Keeping leading zeros and large numbers
Or .NumberFormat = "00000" on your range.
I don't recommend to convert it into a string (unless it is something like a serial number that is not treated as an actual number).
A simpler version compared to Dean's
Sub StrLength()
Dim i As Long, str As String
str = "136"
i = Len(str)
StrLength = String(ExpectedLength - Len(str), "0") & str
End Sub
Small subroutines as these can easily be used as Functions, where you call the function in a regular sub. For example, when you are looping through a range of cells:
Function StrLength(str As String, ExpectedLength As Long) As String
Dim i As Long
i = Len(str)
StrLength = String(ExpectedLength - Len(str), "0") & str
End Function
Sub Test()
Dim c As Range
For each c In ThisWorkbook.Sheets(1).Range("A1:B200")
If Len(c.Value) < 5 Then c.Value = StrLength(Str:=c.Value, ExpectedLength:=5)
Next c
End Sub
I have a columns of strings as follows. How can I put the symbol '<' in between the characters ?
'ABCDE'
'BCG'
'ABCD'
The expected output should be:
A<B<C<D<E
B<C<G
A<B<C<D
=concatenate(left(A1,1),"<",mid(A1,2,1),"<",mid(A1,3,1),(if(len(A1)>3,"<"&mid(A1,4,1)&if(len(A1)>4,"<"&mid(A1,5,1),""),"")))
Will do what you want for values up to 5 letters, and as few as 3 letters. Otherwise you can change it.
Basically it adds a "<" between the first 3 letters and then checks whether the string is longer than 3 letters and if so, adds more "<" characters. If this needs to be more dynamic it's far easier in vba.
A manual, one-off, no-VBA approach would be:
use the Text to Columns tool with Fixed Width and place the markers after each character.
then use a formula like this to append values and separator
The formula could look like this if your values are in row 1
=A1&IF(LEN(B1)>0,">"&B1,"")&IF(LEN(C1)>0,">"&C1,"")&IF(LEN(D1)>0,">"&D1,"")&IF(LEN(E1)>0,">"&E1,"")
Adjust formula to suit the maximum number of characters in a cell.
Such things are not for formulas...
As you tag question as Excel-VBA too, so:
'''''''
Private Sub sb_Test_fp_AddSym()
Debug.Print fp_AddSym("abncd", "<")
End Sub
Public Function fp_AddSym(pStr$, pSym$) As String
Dim i&, j&, iLB&, iUBs&, iUBt&
Dim tSrc() As Byte, tTgt() As Byte, tSym As Byte
tSrc = pStr
tSym = Asc(pSym)
iLB = LBound(tSrc)
iUBs = UBound(tSrc)
iUBt = iUBs * 2 + 3
ReDim tTgt(iLB To iUBt)
For i = iLB To iUBs Step 2
j = i * 2
tTgt(j) = tSrc(i)
tTgt(j + 1) = tSrc(i + 1)
tTgt(j + 2) = tSym
tTgt(j + 3) = 0
Next
ReDim Preserve tTgt(iLB To (iUBt - 4))
Debug.Print tTgt
Stop
fp_AddSym = tTgt
End Function
'''
This worked for me:
Sub SymbolInsert()
Dim cl As Range, temp As String
For Each cl In Range("A1:A3") '~~~> Define your range here
For i = 1 To Len(cl)
temp = temp & Mid(cl, i, 1) & "<"
Next i
cl = IIf(VBA.Right$(temp, 1) = "<", VBA.Left$(temp, Len(temp) - 1), temp)
temp = vbNullString
Next cl
End Sub
It can probably be done with Excel formula for any length, but here is the shortest VBA solution
For Each c In Range("A:A").SpecialCells(xlCellTypeConstants)
c.Value2 = Replace( Left$( StrConv( c, vbUnicode), Len(c) * 2 - 1), vbNullChar, "<")
Next
I have asked here to how put %u after every four digit to convert my long string into a proper unicode text. I got a very nice reply with the UDF and it work great.. now from this string
002006390632064A0632064A00200627064406390645064A0644003A0020062A0645002006270644
I am able to convert it into
%u0020%u0639%u0632%u064A%u0632%u064A%u0020%u0627%u0644%u0639%u0645%u064A%u0644%u003A%u0020%u062A%u0645%u0020%u0627%u0644
Well the string is to long i just showed you the result... Now what I am looking is there any excel function which can convert this into Arabic text. Actually its a uncode and want to see how it look in Arabic.
Currently I am using a website
http://unicode.online-toolz.com/tools/text-unicode-entities-convertor.php
to convert it manually. Is there any excel function which can do that locally.
You could create a byte array from the code and assigning this byte array to a String. This String can then be assigned to a Cell.
Example:
Sub test()
Dim sCode As String
sCode = "002006390632064A0632064A00200627064406390645064A0644003A0020062A0645002006270644"
Dim b() As Byte
Dim j As Long
j = 0
For i = 1 To Len(sCode) Step 4
ReDim Preserve b(j + 1)
b(j) = Val("&H" & Mid(sCode, i + 2, 2))
b(j + 1) = Val("&H" & Mid(sCode, i, 2))
j = j + 2
Next
Dim s As String
s = b
Range("A1").Value = s
End Sub
I need to add brackets around the numbers in a string found in cells on my Excel worksheet.
For example, say I am given:
913/(300+525)
I need to get this in return:
[913]/([300]+[525])
The equations are fairly simple, should only have to deal with + - * / ( ) characters.
I attempted looping through the string character by character using the MID function but I can't get the loop(s) working correctly and end up getting a jumbled mess of random brackets and numbers back. I also considered using regular expressions but I've never used them before and have no idea if this would be a good application.
Please let me know if you need anything else. Thank you for your time!
They can be decently long. Here is another example:
I have:
(544+(1667+1668+1669+1670+1671+1672+1673)-1674)
But I need:
([544]+([1667]+[1668]+[1669]+[1670]+[1671]+[1672]+[1673])-[1674])
I just threw this together but it should work
Function generateBrackets(Equation As String) As String
Dim temp As String
Dim brackets As Boolean
Dim x 'If we're using Option Explicit, or just to be safe
For x = 1 To Len(Equation)
If Not IsNumeric(Mid(Equation, x, 1)) And brackets = False Then
temp = temp & Mid(Equation, x, 1)
ElseIf Not IsNumeric(Mid(Equation, x, 1)) And brackets = True Then
temp = temp & "]" & Mid(Equation, x, 1)
brackets = False
ElseIf IsNumeric(Mid(Equation, x, 1)) And brackets = False Then
temp = temp & "[" & Mid(Equation, x, 1)
brackets = True
ElseIf IsNumeric(Mid(Equation, x, 1)) And brackets = True Then
temp = temp & Mid(Equation, x, 1)
End If
Next x
generateBrackets = temp
End Function
Here is a way which caters for Decimal numbers.
'~~> Add here whatever operators your equation
'~~> is likely to have
Const delim As String = "+()-/"
Sub Sample()
Dim MyAr
Dim sSamp As String
sSamp = "(5.44+(16.67+1668+1669+1670+1671+1672+1673)-1674)"
MyAr = Split(GetNewString(sSamp))
For i = 0 To UBound(MyAr)
sSamp = Replace(sSamp, MyAr(i), "[" & MyAr(i) & "]")
Next i
Debug.Print sSamp
End Sub
Function GetNewString(s As String) As String
Dim sTemp As String
sTemp = s
For i = 1 To Len(delim)
sTemp = Replace(sTemp, Mid(delim, i, 1), " ")
Next i
Do While InStr(1, sTemp, " ")
sTemp = Replace(sTemp, " ", " ")
Loop
GetNewString = Trim(sTemp)
End Function
Input
"(5.44+(16.67+1668+1669+1670+1671+1672+1673)-1674)"
Output
([5.44]+([16.67]+[1668]+[1669]+[1670]+[1671]+[1672]+[1673])-[1674])
So I'm working on a project that has inputs from a fairly clunky database that I have zero control over what type of data it gives me. It basically gives me a string that has numbers in it including decimals.
"take 0.5 Tab by mouth 2 times daily."
Whenever it says tab I want to grab the number before tab and convert it to double format. I know how to use cdbl to convert it once I have the string "0.5" but how I get just that string is kind of difficult since InStr only searches left to right. My thought was to use InStr to find the space before the number that comes before the word "tab" but I'm having trouble figuring out how to code it. Any suggestions?
InStrRev searches right to left. Alternatively, you can use StrReverse and work with the output, but I would use VBScript.Regexp:
Dim text As String
text = "take 0.5 Tab by mouth 2 times daily"
Dim regex As Object
Set regex = CreateObject("VBScript.Regexp")
regex.Global = True
regex.Pattern = "[\d\.]+(?=\sTab)"
Dim test As Object
Set test = regex.Execute(text)
MsgBox (test(0).Value)
Update using Tab as relevant indicator
Assuming that Tab is the relevant indicator you could do the follwing:
Sub ExtractElement()
' column 4 and row 6 contains the text "take 0.5 Tab by mouth 2 times daily"
s = Cells(6, 4).Value
' split text into array for each space
sAr = Split(s, " ")
' iterate over each element of array
For i = 0 To UBound(sAr) - 1
' if the array element "Tab" is reached
If sAr(i) = "Tab" Then
' write the previous array element into the next column
Cells(6, 5).Value = sAr(i-1)
End If
Next
End Sub
Beware that each word is really seperated by a " ". I copied your text and noticed that "Tab by" was not seperated.
Sub ExtractCharCode()
s = Cells(7, 4).Value
For i = 1 To Len(s)
Cells(i, 8).Value = Mid(s, i, 1)
Cells(i, 9).Value = Asc(Mid(s, i, 1))
Next
End Sub
Update using a variation of the answer from user matzone
Instead of passing a range into the function from matzone i would only pass the Value and add a trim to it
Public Function TakeBeforeTab2(s As String) As String
s = Mid(s, 1, InStr(UCase(s), "TAB") - 1)
TakeBeforeTab2 = Trim(Mid(s, InStr(s, " ") + 1))
End Function
To get "0.5" from "take 0.5 Tab by mouth 2 times daily."
Public Function TakeBeforeTab(r As Range) As String
Dim s As String
s = r.Value
s = Mid(s, 1, InStr(UCase(s), "TAB") - 2)
TakeBeforeTab = Mid(s, InStr(s, " ") + 1)
End Function