MS Access Remove Words from Text - vba

I'm trying to remove various words from a text field in MS Access. The data might look like:
Hi there #foo, what's new #bar
#goodfriend and I just watched Star Wars
#this and #that and #theother
I want to remove all the words that start with '#'.
Replace() won't work since the words are different in each record.
Any ideas?

If you're using VBA, you should be able to replace text based on regular expressions. See the answer to replace a column using regex in ms access 2010 as an example.

I actualy upvoted CheeseInPosition's answer but just thought I would provide another way if you can't/don't want to do it with regex. Just wrote a quick function to parse out the words:
Public Function RemoveAtWords(strOriginal As String) As String
Dim strParts() As String
Dim i As Integer
strParts() = Split(strOriginal, " ")
For i = LBound(strParts) To UBound(strParts)
If Left(strParts(i), 1) <> "#" Then
RemoveAtWords = RemoveAtWords & " " & strParts(i)
End If
Next
RemoveAtWords = Trim(RemoveAtWords)
End Function
You can call that from a query and pass through your string. Not as efficient because you have to loop through the whole string, but just another option.

Related

"Query too Complex": MS Access Function to Replace text in Query (Nested Replace())

Purpose: Use a SQL Query in MS Access to locate all records matching specific keywords in a long text field
I am attempting to query for all records in a MS Access DB that have a match on a list of specific keywords within a field. The keywords are as follows:
AIN, ATIN, CKD, AKI, ARF
Issue I'm running into is that the field is a free text entry field, so the formatting of the data is all over the place, and the keywords I'm searching on will often appear in the middle of other full length words (i.e. AIN matches on "pAIN","agAIN", etc), while I only want to include matches on words that are strictly the keywords (i.e. " AIN ", " AKI ").
The idea I'm working with is to simply include matches that will hit on the following format: field_name like '* AIN *'.So basically only include matches that have a space before and after the keyword to limit the number of false positives appearing in the result set.
I have tried writing a SQL query that will normalize the data so that all other characters that appear (".","!","?","#", etc...) will be replaced with a space character (i.e. " AIN!" would be replace(field_name,"!"," ") = " AIN ") with the idea that this should only include words containing only the keyword. In attempting to run my very long nested replace statement in the query, I am receiving the "Query Too Complex" message. Nested replace is as follows:
UCASE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(a.REF_CONTENT_NM,chr(13)," "),chr(10)," "),"`"," "),"~"," "),"!"," "),"#"," "),"#"," "),"$"," "),"%"," "),"^"," "),"&"," "),"*"," "),"("," "),")"," "),"-"," "),"_"," "),"="," "),"+"," "),"["," "),"{"," "),"]"," "),"}"," "),";"," "),":"," "),","," "),"<"," "),"."," "),">"," "),"/"," "),"?"," "),"\"," "),"|"," "),""""," ")) like "* AIN *"
I believe that a workaround would be to create a custom function that could be referenced in the SQL statement, but I am not entirely sure of how to accomplish this. So essentially, I am looking for guidance on how to evaluate a solution of how to normalize the text like the above nested replace statement in Access without running into the "Query Too Complex message". I feel like there is a simple solution that I am just not seeing here, so guidance would be tremendously appreciated!
The main trick to writing a custom function to do this is properly using the ParamArray
This is a small function that executes multiple replaces:
Public Function ReplaceMultiple(strInput As String, strReplace As String, ParamArray Find() As Variant) As String
Dim i As Long
ReplaceMultiple = strInput
For i = LBound(Find) To UBound(Find)
ReplaceMultiple = Replace(ReplaceMultiple, Find(i), strReplace)
Next
End Function
Implement it:
ReplaceMultiple(a.REF_CONTENT_NM, " ", chr(13), chr(10), "`", "etc....")
You might need to think about altering the logic altogether, though, for example keeping a table of characters that should be replaced. I remember something about the max number of arguments being around 20-30, so you might need to use ReplaceMultiple twice.
If you just want to replace everything that isn't a string with a space, you can try the following small function:
Public Function ReplaceNonAlphanumeric(str As String) As String
If str = "" Then Exit Function
Dim i As Long
For i = 1 To Len(str)
If Mid(str, i, 1) Like "[0-9A-z]" Then
ReplaceNonAlphanumeric = ReplaceNonAlphanumeric & Mid(str, i, 1)
Else
ReplaceNonAlphanumeric = ReplaceNonAlphanumeric & " "
End If
Next
End Function

MS Access VBA - Pulling a partial string from semi-consistent data in a field

I've looked around but wasn't able to find an exact solution...
I have an identifier-type field that generally follows the format of XXX-YY-ZZZZZZZZ. Sometimes the number of X's and Z's will vary, but the YY's are always enclosed between the two hyphens. If I wanted to create another field using just the "YY", what would be the best function to use? There's also another reference table with the YYs listed that I intend to relate it to.
Thanks in advance.
Sounds like you want to split the string into an array. Try this out
Public Sub Example()
Dim ExampleStr As String: ExampleStr = "XXX-YY-ZZZZZZZZ"
Dim StrArray() As String
StrArray = Split(ExampleStr, "-")
Debug.Print StrArray(1) ' Return the second element
End Sub

How to count the number of empty spaces in front of a String in VBA?

I have a YAML file which I am reading using VBA Excel plugin. I am getting a String of each line. I need to count the number of empty spaces in the front of the first line so that it will be a marker to find the next key. Let me know how to do that.
Option Explicit
Function empty_spaces(str_input)
empty_spaces = Len(str_input) - Len(LTrim(str_input))
End Function
harun24hr, your answer does not work with " My String " and similar.

Inserting a String inside a String

I want to insert a word inside an existing word? Both are Strings.
For example:
Given String word:
HELLO SAMPLE SENTENCE
i want to insert the word I AM A so my output would be:
HELLO I AM A SAMPLE SENTENCE
i am inserting here basing on the word SAMPLE. So the insertion starts before the word SAMPLE. is this possible?
Based on the description of your logic (which isn't much to go on), I would use:
Dim input As String = "HELLO SAMPLE SENTENCE"
Dim iSample As Integer = input.IndexOf("SAMPLE")
Dim output As String = input.Insert(iSample, "I AM A ")
This uses the BCL function String.Insert, which simply inserts a string into another string at a particular position.
Create a function like this:
Function InsertBefore(sentence As String, find As String, textToInsert As String
Return sentence.Replace(find, textToInsert+Find)
End Function
And call it like this:
sentence = InsertBefore("HELLO SAMPLE SENTENCE", " SAMPLE ", "I AM A")
If I remember correctly, you can use the String.split() function on your string.
See DotNetPerls' page on Split here.
You can split the string into an array, then insert the line you want into the array, then join them back together using String.Join() (thanks Monty, I don't use Visual Basic that frequently anymore, I forgot that :)).
Hope this help :)

MS-Access: Replace "bracket"

In one of the ms-access table I work with we have a text field with a set size.
At the end of this field there is some extra code that varies depending on the situation.
I'm looking for a way to remove one of these code but even when the last part is truncated by the field maximum size.
Let's call the field "field" and the code I'm looking to remove "abc-longcode".
If I use the replace SQL function with the string abc-longcode the query will only work when the code is complete.
If I also want my update query (that does nothing but remove this specific code at the end of my field) to work on incomplete codes how would that translate into ms-SQL?
It would have to remove (or replace with "" to be precise) all of the following (example of course, not the real codes):
abc-longcode
abc-longcod
abc-longco
abc-longc
abc-long
abc-lon
abc-lo
abc-l
Obviously I could do that with several queries. Each one replacing one of the expected truncated codes... but it doesn't sound optimal.
Also, when the field is big enough to get all of the code, there can sometime be extra details at the end that I'll also want to keep so I cannot either just look for "abc-l" and delete everything that follows :\
This query (or queries if I can't find a better way) will be held directly into the .mdb database.
So while I can think of several ways to do this outside of a ms-sql query, it doesn't help me.
Any help?
Thanks.
You can write a custom VBA replace method that will replace any of the given cases {"abc-longcode", ... "abc-l"}. This is essentially the same tack as your "several queries" idea, except it would only be one query. My VBA is rusty, but something like:
public function ReplaceCodes(str as string) as string
dim returnString as string
returnString = str
returnString = replace(returnString,"abc-longcode","")
// ... etc...
ReplaceCodes = returnString
end function
I may have gotten the parameter order wrong on replace :)
I would use my own custom function to do this using the split function to get the first part of the string. You can then use that value in the update query.
Public Function FirstPart(thetext As String) As String
Dim ret As String
Dim arrSplitText As Variant
arrSplitText = Split(thetext, "-")
ret = arrSplitText(0)
FirstPart = ret
End Function
Can you use:
Left(FieldX,InStr(FieldX,"abc-")-1)
EDIT re Comment
If there is a space or other standard delimiter:
IIf(InStr(InStr(FieldX, "abc-"), FieldX, " ") = 0, Left(FieldX, InStr(FieldX, "abc-") - 1), Replace(FieldX, Mid(FieldX, InStr(FieldX, "abc-"), InStr(InStr(FieldX, "abc-"), FieldX, " ") - InStr(FieldX, "abc-")), ""))