searching for 3" in a string using InStr() vba - string

I'm trying to search for a string which includes a doubel quote ". ex. search for the string 3" in the larger string 43-9120-BT-1207-3"-150H21-NI. Currently this is what I have.
Dim line As String
line = "43-9120-BT-1207-3"-150H21-NI"
If InStr(1, line, Str$(34) & 3" & Str$(34)) > 0 Then
.
.
.
end if
I can never get into the if statement, tried many combinations of Str$(34)s and multiple "s but I get the error
Expected: List operator
Anyone can explain how to search for a string with a double quote at the end of it?

This will find 3" in your line string:
'assuming:
'activecell = 43-9120-BT-1207-3"-150H21-NI
'next:
line = activecell
'search for 3"
If InStr(1, line, "3" & Chr(34)) > 0 Then MsgBox "OK"

If the line is hardcoded, you need to escape it, by doubling the double quotes:
line = "43-9120-BT-1207-3""-150H21-NI"
Also these are double quotes ", these are single quotes ', you might want to change your question a bit.
Edit : correcting your second line as well.
If InStr(1, line, "3""" ) > 0 Then

Related

Replace weird or special character in a string

I'm trying to convert a Excel file into a SQL query. My problem is that there are special characters in the file I was given. I cant replace them CTRL+H because they dont show at all in the Excel file. When I write my query(either in utf8 or ANSI), they show. With Ultra-Edit, they show as HEX C2 92. With Notepad++ in utf8, they show as PU2. In ANSI, they show as Â’. I suspect it's an apostrophe. This is a french file by the way.
So far I tried to put it in a string and do these operations, but nothing worked.
Dim Line as String
Line = Wb.Worksheets(1).Cells(LineNo, ColNo)
Line = Replace(Line, "Â’", "''")
Line = Replace(Line, "’", "''")
Line = Replace(Line, "Â", "''")
Line = Replace(Line, Chr(194) & Chr(146), "''") 'decimal value of C2 92
Line = Replace(Line, Chr(146) & Chr(194), "''") 'inverted decimal value of C2 92
Thanks!
Instead of trying to eliminate various junk characters, try to focus on keeping only the good ones. Say we know valid characters are upper and lower case letters, numbers, and the underscore. This code will keep only the good ones:
Public Function KeepOnlyGood(s As String) As String
Dim CH As String, L As Long, i As Long
KeepOnlyGood = ""
L = Len(s)
For i = 1 To L
CH = Mid(s, i, 1)
If CH Like "[0-9a-zA-Z]" Or CH = "_" Then
KeepOnlyGood = KeepOnlyGood & CH
End If
Next i
End Function
If you want to replace junk with a space, the code can be modified to do just that.

MS Access: How do I remove the 13 leading spaces of this field?

I have a table where one of the fields has 13 leading spaces (no visible characters in them). I tried TRIM() and REPLACE([Field1], " ", "") but neither one worked. Could anyone venture a guess as to what's going on and how to fix this?
This is not an answer but it will allow you to see what the chr value is for the string. Just call it like MsgBox WhatAreTheAscValues([Field1]) and you will see what value the characters that make up the string and allow you to adjust your code accordingly.
Function WhatAreTheAscValues(str As String)
Dim i As Integer
Dim answer As String
answer = "The Chr(x) values in this string are listed below" & vbCrLf
For i = 1 To Len(str)
answer = answer + CStr(Asc(Mid(str, i, 1))) & ", "
Next i
WhatAreTheAscValues = Left(answer, Len(answer) - 2)
End Function

VBA Trim leaving leading white space

I'm trying to compare strings in a macro and the data isn't always entered consistently. The difference comes down to the amount of leading white space (ie " test" vs. "test" vs. " test")
For my macro the three strings in the example should be equivalent. However I can't use Replace, as any spaces in the middle of the string (ex. "test one two three") should be retained. I had thought that was what Trim was supposed to do (as well as removing all trailing spaces). But when I use Trim on the strings, I don't see a difference, and I'm definitely left with white space at the front of the string.
So A) What does Trim really do in VBA? B) Is there a built in function for what I'm trying to do, or will I just need to write a function?
Thanks!
So as Gary's Student aluded to, the character wasn't 32. It was in fact 160. Now me being the simple man I am, white space is white space. So in line with that view I created the following function that will remove ALL Unicode characters that don't actual display to the human eye (i.e. non-special character, non-alphanumeric). That function is below:
Function TrueTrim(v As String) As String
Dim out As String
Dim bad As String
bad = "||127||129||141||143||144||160||173||" 'Characters that don't output something
'the human eye can see based on http://www.gtwiki.org/mwiki/?title=VB_Chr_Values
out = v
'Chop off the first character so long as it's white space
If v <> "" Then
Do While AscW(Left(out, 1)) < 33 Or InStr(1, bad, "||" & AscW(Left(out, 1)) & "||") <> 0 'Left(out, 1) = " " Or Left(out, 1) = Chr(9) Or Left(out, 1) = Chr(160)
out = Right(out, Len(out) - 1)
Loop
'Chop off the last character so long as it's white space
Do While AscW(Right(out, 1)) < 33 Or InStr(1, bad, "||" & AscW(Right(out, 1)) & "||") <> 0 'Right(out, 1) = " " Or Right(out, 1) = Chr(9) Or Right(out, 1) = Chr(160)
out = Left(out, Len(out) - 1)
Loop
End If 'else out = "" and there's no processing to be done
'Capture result for return
TrueTrim = out
End Function
TRIM() will remove all leading spaces
Sub demo()
Dim s As String
s = " test "
s2 = Trim(s)
msg = ""
For i = 1 To Len(s2)
msg = msg & i & vbTab & Mid(s2, i, 1) & vbCrLf
Next i
MsgBox msg
End Sub
It is possible your data has characters that are not visible, but are not spaces either.
Without seeing your code it is hard to know, but you could also use the Application.WorksheetFunction.Clean() method in conjunction with the Trim() method which removes non-printable characters.
MSDN Reference page for WorksheetFunction.Clean()
Why don't you try using the Instr function instead? Something like this
Function Comp2Strings(str1 As String, str2 As String) As Boolean
If InStr(str1, str2) <> 0 Or InStr(str2, str1) <> 0 Then
Comp2Strings = True
Else
Comp2Strings = False
End If
End Function
Basically you are checking if string1 contains string2 or string2 contains string1. This will always work, and you dont have to trim the data.
VBA's Trim function is limited to dealing with spaces. It will remove spaces at the start and end of your string.
In order to deal with things like newlines and tabs, I've always imported the Microsoft VBScript RegEx library and used it to replace whitespace characters.
In your VBA window, go to Tools, References, the find Microsoft VBScript Regular Expressions 5.5. Check it and hit OK.
Then you can create a fairly simple function to trim all white space, not just spaces.
Private Function TrimEx(stringToClean As String)
Dim re As New RegExp
' Matches any whitespace at start of string
re.Pattern = "^\s*"
stringToClean = re.Replace(stringToClean, "")
' Matches any whitespace at end of string
re.Pattern = "\s*$"
stringToClean = re.Replace(stringToClean, "")
TrimEx = stringToClean
End Function
Non-printables divide different lines of a Web page. I replaced them with X, Y and Z respectively.
Debug.Print Trim(Mid("X test ", 2)) ' first place counts as 2 in VBA
Debug.Print Trim(Mid("XY test ", 3)) ' second place counts as 3 in VBA
Debug.Print Trim(Mid("X Y Z test ", 2)) ' more rounds needed :)
Programmers prefer large text as may neatly be chopped with built in tools (inSTR, Mid, Left, and others). Use of text from several children (i.e taking .textContent versus .innerText) may result several non-printables to cope with, yet DOM and REGEX are not for beginners. Addressing sub-elements for inner text precisely (child elements one-by-one !) may help evading non-printable characters.

Excel - VBA : Make the "replace" function more specific

I am currently encountering a problem which doesn't seem that hard to fix but, yet, I can't find a clean way of doing it on my own.
I am using the "Replace" function to change some expressions in a sentence typed by an user. For example, if the user types "va", I want it to be turned into "V. A." instead so it will match more easily with my database for further operations.
Here is my simple code to do it :
sMain.Range("J3").Replace "VA", "V. A."
It works well.
Problem is, it's not only spotting "VA" as an individual expression, but also as a part of words.
So if my user types "Vatican", it's gonna turn it into : "V. A.tican"... which of course I don't want.
Do you know how to easily specify my code to make it ONLY consider replacing the whole words matching the expression? (I have dozens of lines of these replacement so ideally, it would be better to act directly on the "replace" functions - if possible).
Thanks in advance !
Do this:
sMain.Range("J3").Replace " VA ", "V. A."
then handle the cases where the original string starts or ends with VA
also, handle all cases of separators which could be (for example) tab, space or comma.
To do that:
const nSep As Integer = 3
Dim sep(nSep) As String
sep(1) = " "
sep(2) = vbTab
sep(3) = ","
for i=1 to nSep
for j=1 to nSep
sMain.Range("J3").Replace sep(i) & "VA" & sep(j), "V. A."
next
next
Can split it up and check each word. I have put it into a function for easy of use and flexibility.
Function ReplaceWordOnly(sText As String, sFind As String, sReplace As String) As String
On Error Resume Next
Dim aText As Variant, oText As Variant, i As Long
aText = Split(sText, " ")
For i = 0 To UBound(aText)
oText = aText(i)
' Check if starting with sFind
If LCase(Left(oText, 2)) = LCase(sFind) Then
Select Case Asc(Mid(oText, 3, 1))
Case 65 To 90, 97 To 122
' obmit if third character is alphabet (checked by ascii code)
Case Else
aText(i) = Replace(oText, sFind, sReplace, 1, -1, vbTextCompare)
End Select
End If
Next
ReplaceWordOnly = Join(aText, " ")
End Function
Example output:
?ReplaceWordOnly("there is a vatican in vA.","Va","V. A.")
there is a vatican in V. A..

How to remove the last occurrence of a character within a string?

I'm currently writing a function that dynamically composes a sql-query to retreive a number of posts and I've run into a smaller problem.
Pseudocode:
if trim$(sSqlQuery) <> "" then
sSqlQuery = "foo foo ) foo"
end if
if 1 = 1 then
sSqlQuery = sSqlQuery & "bar bar bar"
end if
This function returns the correct sql-query most of the time, but due to some circumstances in the earlier functions before this one, the second if-clause will be triggered. Resulting in weird query-results.
What i need to do is to figure out how to remove the last occurrence of ")" within sSqlQuery before it appends the second set of query to the total query within the second if-clause.
In pseudo I think it'd look something like this:
if 1 = 1 then
call removeLastOccurringStringFromString(sSqlQuery, ")")
sSqlQuery = sSqlQuery & "bar bar bar"
end if
However, i find it really hard to get a grasp on the Right() Left() and Mid() functions.
What I have tried is this:
nLen = InStrRev(sSqlSokUrval, ")") ' To get the positional value of the last ")"
After that i'm completely lost. Since if I substring this with Mid() i'll only get the ")" and nothing else.
Any thoughts and/or hint's on how to go about solving this will be highly appreciated! Thanks!
'Searches subject and removes last (and *only* last) occurence of the findstring
Function RemoveLastOccurenceOf(subject, findstring)
Dim pos
'Find last occurence of findstring
pos = InstrRev(subject, findstring, -1, vbBinaryCompare) 'use vbTextCompare for case-INsensitive search
if pos>0 then 'Found it?
'Take left of subject UP UNTIL the point where it was found
'...Skip length of findstring
'...Add rest of string
RemoveLastOccurenceOf = Left(subject, pos - 1) & Mid(subject, pos + len(findstring))
else 'Nope
'Return entire subject
RemoveLastOccurenceOf = subject
end if
End Function

Resources