VB code to remove special character in a column - vba

I am having a column which contains integer values with two special character "," and "_". I am trying to remove these character for example 1,10_2,2_3,3 should be like 1102233. Thanks in advance for your suggestions.

this function isn't foolproof but it is a good start.
Function trim(aStringToTrim As String, aElementToTrinm() As Variant) As String
Dim elementToTrim As Integer
Dim IndexInString As Integer
For elementToTrim = LBound(aElementToTrinm) To UBound(aElementToTrinm)
IndexInString = InStr(aStringToTrim, aElementToTrinm(elementToTrim))
Do While IndexInString > 0
aStringToTrim = Left(aStringToTrim, IndexInString - 1) & Right(aStringToTrim, Len(aStringToTrim) - IndexInString - Len(aElementToTrinm(elementToTrim)) + 1)
IndexInString = InStr(aStringToTrim, aElementToTrinm(elementToTrim))
Loop
Next
End Function
It can be use like this:
Sub main()
Dim myString As String
Dim caracterstoRemove As Variant
caracterstoRemove = Array(",", ".")
myString = "This, is. a, string, with. caracters to remove."
myString = trim(myString, caracterstoRemove)
End Sub

Related

VBA Split a String in two parts

I'm trying to obtain two codes from this string: "HL PNX-70[15200]"
But with this code, I obtain two times the same output: "HL PNX-70". So, the code is not properly done.
How to obtain the output '15200' from the above mentioned String?
Code:
Private Sub Comando221_Click()
MsgBox (Right(Split("HL PNX-70[15200]", "[")(0), 50))
MsgBox (Left(Split("HL PNX-70[15200]", "[")(0), 50))
End Sub
Are you looking for this ?
Sub Test()
MsgBox Split("HL PNX-70[15200]", "[")(0)
MsgBox Replace(Split("HL PNX-70[15200]", "[")(1), "]", "")
End Sub
Split returns a zero-based array so you are interested in the second element, index 1. Both lines of your code are extracting "HL PNX-70" and the leftmost and rightmost 50 characters will clearly be the same.
This code illustrates two ways of extracting the desired string for your specific example, but it is not necessarily ironclad if you are working with multiple different types of string. You could also use Instr, as per the other answer, or look at regular expressions if you need more complex pattern matching.
Sub y()
Dim s As String, v
s = "HL PNX-70[15200]"
v = Split(s, "[")
Debug.Print v(0) 'HL PNX-70
Debug.Print v(1) '15200]
MsgBox Left(v(1), Len(v(1)) - 1) '15200
v = Split(v(1), "]")
MsgBox v(0) '15200
End Sub
You could try:
Option Explicit
Sub Test()
Dim str As String, Result As String
Dim Start_Point As Long, No_Characters As Long
str = "HL PNX-70[15200]"
Start_Point = InStr(str, "[") + 1
No_Characters = Len(str) - Start_Point
Result = Mid(str, Start_Point, No_Characters)
Debug.Print Result
End Sub
Here is your code
Dim text, text1, text2 As String
text = "HL PNX-70[15200]"
text1 = Break_String(CStr(text), 0)
text2 = Break_String1(Break_String(CStr(text), 1))
Function Break_String(a As String, pos As Integer) As String
Dim WrdArray() As String
WrdArray() = Split(a, "[")
Break_String = WrdArray(pos)
End Function
Function Break_String1(a As String) As String
Dim WrdArray() As String
WrdArray() = Split(a, "]")
Break_String1 = WrdArray(0)
End Function

vba runtime error 424 object required - string indexing

I looked at the other links and none seem to help me out. I am writing code for a program that will count all the commas in a phrase. I am not new to programming but I am new to VBA.
Sub examp()
Dim s As String
Dim i, my_c As Integer
i = 0
s = ",jkqk;j,oiheqfjnq;ef,jwhef;ur,jwefun;jwkbnf," '<-------arbitrary, however, when I tried to make it input from a textbox it gave me error 424 as well, so I just defined it as random chars with commas
While i < Len(s)
For i = 0 To Len(s) - 1
j = s.Chars(i) <----------------------------------Error occurs here
If j = "," Then
my_c = my_c + 1
End If
Next i
Wend
Count.Text = "my_c"
End Sub
change j = s.Chars(i) to j = Mid(s,i,1)
in line Dim i, my_c As Integer only my_c is Integer, but i
is Variant. You should declare each variable explicitly: Dim i As Integer, my_c As Integer
not sure what exactly is your Count (maybe textbox), but use
Count.Text = my_c without quotes.
also I can't undersand why do you use two loops? While i < Len(s)
is odd.
For i = 0 To Len(s) - 1 should be For i = 1 To Len(s)
If you want to count commas, there is more efficient way:
Dim s As String
Dim my_c As Integer
s = ",jkqk;j,oiheqfjnq;ef,jwhef;ur,jwefun;jwkbnf,"
my_c = Len(s) - Len(Replace(s, ",", ""))
Or you can try this:
Sub test()
Dim s As String
Dim c
Dim my_c As Long
s = ",jkqk;j,oiheqfjnq;ef,jwhef;ur,jwefun;jwkbnf,"
c = Split(s, ",")
my_c = UBound(c)
Debug.Print my_c
End Sub

Encrypter with Key and Message - VB.Net

Okay, so I am trying to make my program take whatever your key is, and loop through each character of the key, then find the ascii code for each character code, and then loop through each character of the message, finding the ascii code of each of them, and adding the key code to the message code, doing this for each character in the key, to each character in the message. I ran into a little problem, it changes the message right after the first letter is added, and I can't figure out how to fix it, any help would be great!
Basically, all I want is to that the ascii code for the key characters and add them to the ascii code for the message characters, then convert that final code back to the new characters in the message text. Using this:
tbxMessage.Text = (AscW(Mid(tbxMessage.Text, xForMess, 1)) + AscW(vTemp))
Here is everything I've got so far:
Public Class Form1
Function fctEncryptDecrypt(pMess As String, pKey As String) As String
If Len(tbxMessage.Text) > 0 Then
Dim xForKey As Integer
Dim xForMess As Integer
Dim intKey As Integer
Dim intMessage As Integer
Dim strAsciiKeyChar As String
Dim intAsciiKeyChar As Integer
Dim strAsciiMesChar As String
Dim intAsciiMesChar As Integer
Dim vTemp As String
Dim vTempMess As String
intKey = Len(tbxKey.Text)
intMessage = Len(tbxMessage.Text)
For xForKey = 1 To intKey
strAsciiKeyChar = Mid(tbxKey.Text, xForKey, 1)
intAsciiKeyChar = AscW(strAsciiKeyChar)
vTemp = intAsciiKeyChar
For xForMess = 1 To intMessage
strAsciiMesChar = Mid(tbxMessage.Text, xForMess, 1)
intAsciiMesChar = AscW(strAsciiMesChar)
vTempMess = vTemp + intAsciiMesChar
tbxMessage.Text = (AscW(Mid(tbxMessage.Text, xForMess, 1)) + AscW(vTemp))
Next xForMess
Next xForKey
Label1.Text = vTemp
Else
MessageBox.Show("No Message Found")
End If
End Function
Private Sub btnEncrypt_Click(sender As System.Object, e As System.EventArgs) Handles btnEncrypt.Click
fctEncryptDecrypt(tbxMessage.Text, tbxKey.Text)
End Sub
End Class
tbxMessage.Text = (AscW(Mid(tbxMessage.Text, xForMess, 1)) + AscW(vTemp))
in the inner For loop is setting the value of the text box to a number.
I'd expect the use of a temporary string variable that collects
Chr((intAsciiKeyChar + intAsciiMesChar) mod 256)
I'd also expect the key to be applied one letter at a time over the message. Something like:
Dim i as Integer
Dim s as String
Dim sKey as String
Dim sMesg as String
Dim intCharacter as Integer
s = ""
For i = 1 to len(tbxMessage.Text)
sKey = Mid(tbxKey.Text, (i mod Len(tbxKey)) + 1, 1)
sMesg = Mid(tbxMessage.Text, i, 1)
intCharacter = (WAsc(sKey) + WAsc(sMesg)) mod 256
s = s & Chr(intCharacter)
Next
tbxMessage.Text = s

Spliting a string in VBA to get a list of numeric values

I would like to split the following string "2/3/4/4" for example and get each number and save them as a list.
I can split the string with the code split("2/3/4/4", "/") but then I cannot manage to put them in a list.
Any help is appreciated.
Yes, like engineersmnky says you can just return the results of Split() to a String array, like this:
Public Sub Test()
Dim results() As String
Dim i As Integer
results = Split("2/3/4/4", "/")
For i = LBound(results) To UBound(results)
MsgBox results(i)
Next i
End Sub
This would split "2/3/4/4" and put the numbers in A1:A4
Sub SplitAndList()
Dim nums As Variant, n As Integer
nums = Split("2/3/4/4", "/")
For n = 0 To UBound(nums)
Range("A" & n + 1) = nums(n)
Next n
End Sub

VBA. How to find position of first digit in string

I have string "ololo123".
I need get position of first digit - 1.
How to set mask of search ?
Here is a lightweight and fast method that avoids regex/reference additions, thus helping with overhead and transportability should that be an advantage.
Public Function GetNumLoc(xValue As String) As Integer
For GetNumLoc = 1 To Len(xValue)
If Mid(xValue, GetNumLoc, 1) Like "#" Then Exit Function
Next
GetNumLoc = 0
End Function
Something like this should do the trick for you:
Public Function GetPositionOfFirstNumericCharacter(ByVal s As String) As Integer
For i = 1 To Len(s)
Dim currentCharacter As String
currentCharacter = Mid(s, i, 1)
If IsNumeric(currentCharacter) = True Then
GetPositionOfFirstNumericCharacter = i
Exit Function
End If
Next i
End Function
You can then call it like this:
Dim iPosition as Integer
iPosition = GetPositionOfFirstNumericCharacter("ololo123")
Not sure on your environment, but this worked in Excel 2010
'Added reference for Microsoft VBScript Regular Expressions 5.5
Const myString As String = "ololo123"
Dim regex As New RegExp
Dim regmatch As MatchCollection
regex.Pattern = "\d"
Set regmatch = regex.Execute(myString)
MsgBox (regmatch.Item(0).FirstIndex) ' Outputs 5
I actually have that function:
Public Function GetNumericPosition(ByVal s As String) As Integer
Dim result As Integer
Dim i As Integer
Dim ii As Integer
result = -1
ii = Len(s)
For i = 1 To ii
If IsNumeric(Mid$(s, i, 1)) Then
result = i
Exit For
End If
Next
GetNumericPosition = result
End Function
You could try regex, and then you'd have two problems. My VBAfu is not up to snuff, but I'll give it a go:
Function FirstDigit(strData As String) As Integer
Dim RE As Object REMatches As Object
Set RE = CreateObject("vbscript.regexp")
With RE
.Pattern = "[0-9]"
End With
Set REMatches = RE.Execute(strData)
FirstDigit = REMatches(0).FirstIndex
End Function
Then you just call it with FirstDigit("ololo123").
If speed is an issue, this will run a bit faster than Robs (noi Rob):
Public Sub Example()
Const myString As String = "ololo123"
Dim position As Long
position = GetFirstNumeric(myString)
If position > 0 Then
MsgBox "Found numeric at postion " & position & "."
Else
MsgBox "Numeric not found."
End If
End Sub
Public Function GetFirstNumeric(ByVal value As String) As Long
Dim i As Long
Dim bytValue() As Byte
Dim lngRtnVal As Long
bytValue = value
For i = 0 To UBound(bytValue) Step 2
Select Case bytValue(i)
Case vbKey0 To vbKey9
If bytValue(i + 1) = 0 Then
lngRtnVal = (i \ 2) + 1
Exit For
End If
End Select
Next
GetFirstNumeric = lngRtnVal
End Function
An improved version of spere's answer (can't edit his answer), which works for any pattern
Private Function GetNumLoc(textValue As String, pattern As String) As Integer
For GetNumLoc = 1 To (Len(textValue) - Len(pattern) + 1)
If Mid(textValue, GetNumLoc, Len(pattern)) Like pattern Then Exit Function
Next
GetNumLoc = 0
End Function
To get the pattern value you can use this:
Private Function GetTextByPattern(textValue As String, pattern As String) As String
Dim NumLoc As Integer
For NumLoc = 1 To (Len(textValue) - Len(pattern) + 1)
If Mid(textValue, NumLoc, Len(pattern)) Like pattern Then
GetTextByPattern = Mid(textValue, NumLoc, Len(pattern))
Exit Function
End If
Next
GetTextByPattern = ""
End Function
Example use:
dim bill as String
bill = "BILLNUMBER 2202/1132/1 PT2200136"
Debug.Print GetNumLoc(bill , "PT#######")
'Printed result:
'24
Debug.Print GetTextByPattern(bill , "PT#######")
'Printed result:
'PT2200136