I have created the following Regular expression in javascript to test if the string works.
var str = "Test [abc] =1234= (PG1/2)";
var pattern = /[\[]/;
var pattern1 = /[\]]/;
var pattern2 = /[=?]/;
var pattern3 = /[\(]+[A-z0-9\/]+[\)]/;
var result = str.replace(pattern1, "").replace(pattern,"").replace(pattern2, "[").replace(pattern2,"]").replace(pattern3,"");
which works perfectly fine. However no i have tried to convert this SQL (using the ms access sample database)
i have tried the following which hasn't worked as i get an error.
UPDATE Orders
SET Orders.ShipName=replace(replace( Orders.ShipName, "/[\[]/", ''), "/[\]]/",'');
which didn't work. I think I've gone about the wrong approach to the SQL. can anyone advise on the correct way to do this? as all of the replaces are required to be executed on the Orders.ShipName field. Is this even possible?
The standard Replace() function in Access does not support pattern matching using regular expressions, but you could "roll your own" in VBA quite easily:
Option Compare Database
Option Explicit
Public Function MyRegexReplace( _
originalText As Variant, _
regexPattern As String, _
replaceText As String) As Variant
' VBA Project Reference required:
' Microsoft VBScript Regular Expressions 5.5
Dim rtn As Variant
Dim objRegExp As RegExp, objMatch As Match, colMatches As MatchCollection
rtn = originalText
If Not IsNull(rtn) Then
Set objRegExp = New RegExp
objRegExp.pattern = regexPattern
Set colMatches = objRegExp.Execute(originalText)
For Each objMatch In colMatches
rtn = _
Left(rtn, objMatch.FirstIndex) & _
replaceText & _
Mid(rtn, objMatch.FirstIndex + objMatch.length + 1)
Next
Set objMatch = Nothing
Set colMatches = Nothing
Set objRegExp = Nothing
End If
MyRegexReplace = rtn
End Function
Some VBA test code for the example in your question would be
Private Sub testcode()
Dim str As String
Dim pattern As String, pattern1 As String, pattern2 As String, pattern3 As String
Dim result As String
str = "Test [abc] =1234= (PG1/2)"
pattern = "[\[]"
pattern1 = "[\]]"
pattern2 = "[=?]"
pattern3 = "[\(]+[A-z0-9\/]+[\)]"
result = str
result = MyRegexReplace(result, pattern1, "")
result = MyRegexReplace(result, pattern, "")
result = MyRegexReplace(result, pattern2, "[")
result = MyRegexReplace(result, pattern2, "]")
result = MyRegexReplace(result, pattern3, "")
Debug.Print result ' Test abc [1234]
End Sub
If you needed to perform multiple "inline" replacements in a query you could still nest the calls to your function as you did before:
UPDATE Orders
SET ShipName = MyRegexReplace(MyRegexReplace(ShipName, "[\]]", ""), "[\[]", "")
For more details on Microsoft Regular Expressions see:
How To Use Regular Expressions in Microsoft Visual Basic 6.0
Following my comment:
Public Function RegexReplace( _
originalText As Variant, _
regexPattern As String, _
replaceText As String) As Variant
Dim rtn As Variant
Dim objRegExp As Object
Dim objMatch As Match, colMatches As MatchCollection
Dim dif As Integer
rtn = originalText
If Not IsNull(rtn) Then
Set objRegExp = CreateObject("VBScript.RegExp")
objRegExp.pattern = regexPattern
objRegExp.IgnoreCase = False
objRegExp.Global = True
Set colMatches = objRegExp.Execute(originalText)
dif = 0
For Each objMatch In colMatches
rtn = Left(rtn, objMatch.FirstIndex + dif) & replaceText & _
Mid(rtn, objMatch.FirstIndex + dif + objMatch.length + 1)
dif = Len(replaceText) - objMatch.length
Next
Set objMatch = Nothing
Set colMatches = Nothing
Set objRegExp = Nothing
End If
RegexReplace = rtn
End Function
Related
I'm using Application.FileDialog(msoFileDialogFolderPicker) to pick a folder and it handles well folders with utf8 names.
But when I try to Debug.Print the result of SelectedItems(1) or save it to a config file or do anything, I loose the accents of the folder.
For example:
Original folder:
"D:\Śākta"
'Debug.Print' or saving into an utf8 file result saves:
"D:\Sakta" (removed all the accents)
The problem is that I try to save the selected folder to a config file and when I try to load it, next time it will of course won't recognize as a real folder because of the missing accents.
How to get the real name of the folder with the accents to be able to save it after, not this "representation" of it?
Update:
Just checked, and even the InputBox kills the accents!
#John Coleman's answer solved the issue switching the file saving to 'ADODB.Stream'
Here is an example of reading and writing config file supporting UTF8:
Public Function fileExists(ByVal fullFilename As String) As Boolean
fileExists = CreateObject("Scripting.FileSystemObject").fileExists(fullFilename)
End Function
Public Function ReadTextFile(ByVal sPath As String) As String
If fileExists(sPath) Then
Dim fsT As Object
Set fsT = CreateObject("ADODB.Stream")
fsT.Mode = adModeRead
fsT.Type = 2 'Specify stream type - we want To save text/string data.
fsT.Charset = "utf-8" 'Specify charset For the source text data.
fsT.Open 'Open the stream And write binary data To the object
fsT.LoadFromFile (sPath)
ReadTextFile = fsT.ReadText
fsT.Close
Set fsT = Nothing
Else
ReadTextFile = ""
End If
End Function
Public Function WriteTextFile(ByVal s As String, ByVal sPath As String) As Boolean
Dim objStreamUTF8NoBOM: Set objStreamUTF8NoBOM = CreateObject("ADODB.Stream")
Dim fsT As Object
Set fsT = CreateObject("ADODB.Stream")
fsT.Type = 2 'Specify stream type - we want To save text/string data.
fsT.Charset = "utf-8" 'Specify charset For the source text data.
fsT.Open 'Open the stream And write binary data To the object
fsT.WriteText s
fsT.Position = 0
fsT.SaveToFile sPath, 2 'Save binary data To disk
fsT.Position = 3
With objStreamUTF8NoBOM
.Type = 1
.Open
fsT.CopyTo objStreamUTF8NoBOM
.SaveToFile sPath, 2
Close
End With
fsT.Close
Set fsT = Nothing
Set objStreamUTF8NoBOM = Nothing
End Function
Function SetSettings(ByVal Keyname As String, ByVal Wstr As String) As String
Dim settingsFileContent
settingsFileContent = ReadTextFile(IniFileName)
Set RE = CreateObject("VBScript.RegExp")
RE.Pattern = Keyname + "=.*"
RE.MultiLine = 1
If RE.Test(settingsFileContent) Then
settingsFileContent = RE.Replace(settingsFileContent, Keyname + "=" + Wstr)
Else
settingsFileContent = settingsFileContent + IIf(Len(settingsFileContent) = 0, "", vbNewLine) + Keyname + "=" + Wstr
End If
WriteTextFile settingsFileContent, IniFileName
SetSettings = Wstr
End Function
Private Function GetSettings(ByVal Keyname As String) As String
Dim settingsFileContent As String
settingsFileContent = ReadTextFile(IniFileName)
Set RE = CreateObject("VBScript.RegExp")
RE.MultiLine = 1
RE.Global = 1
RE.Pattern = "\r"
settingsFileContent = RE.Replace(settingsFileContent, "")
RE.Global = 0
RE.Pattern = "^" + Keyname + "=(.*)"
Set allMatches = RE.Execute(settingsFileContent)
If allMatches.Count <> 0 Then
Debug.Print (Keyname + ": """ + allMatches.Item(0).SubMatches.Item(0) + """")
GetSettings = allMatches.Item(0).SubMatches.Item(0)
Else
GetSettings = ""
End If
End Function
I have the a string in below format
Dim str as String = "[1_5],[1_3],[1_5]"
The part before the _ can be variable is not a fix number
i need to convert it in to format
"5,3,5"
i have used the below code to obtain all the number that i need in the new string in the matches Item Groups
Dim pattern As String = "_(.*?)\]"
Dim matches As MatchCollection =
Regex.Matches(rowpanel.getRequestedArea_selectionArea(), pattern, RegexOptions.Singleline)
My question is how i can join all the Groups to obtain the final string format ?
A Regex solution could be
Dim x = matches.Select(Function(g) g.Groups(1).Value)
Dim final = String.Join(",", x)
A Split and Join one is
Dim blocks As String() = str.Split(",")
Dim result = New List(Of String)()
For Each s In blocks
result.Add(s.Split("_")(1).Trim("]"))
Next
Dim final = String.Join(",", result)
You can do something like this using RegEx and replace:
Dim str As String = "[1_5],[1_3],[1_5]"
Dim RegX As Regex = New Regex("\[\d{1}_")
Dim match As Match = RegX.Match(str)
If match.Success Then
str = Replace(str, match.Value, "")
str = Replace(str, "]", "")
End If
Alternative with simple and readable loop but multiple lines of code wrapped with a method
Public Function ExtractNumbers(text As String) As String
Dim current As New StringBuilder()
Dim write As Boolean = False
For Each character As Char In text
If character = "_"c Then
write = True
Continue For
End If
If character = "]"c Then
write = False
current.Append(",")
Continue For
End If
If write Then
current.Append(character)
Continue For
End If
Next
current.Length -= 1
Return current.ToString()
End Function
Usage
var extracted = ExtractNumbers("[1_5],[1_3],[1_5]")
Console.WriteLine(extracted)
' 5,3,5
I am trying to connect MS Word to Microsoft's QnAMaker using VBA to help answer a wide variety of similar questions I receive.
My idea is select the question and then have vba query the answer and copy it to the clipboard (templates for replies are different, this way I can select where to output the answer).
Any help is appreciated. Thank you.
(I am using this JSON library: https://github.com/VBA-tools/VBA-JSON)
I have already applied the suggested solutions described in the issue section below: https://github.com/VBA-tools/VBA-JSON/issues/68
Sub copyAnswer()
'User Settings
Dim questionWorksheetName As String, questionsColumn As String,
firstQuestionRow As String, kbHost As String, kbId As String, endpointKey
As String
Dim str As String
str = Selection.Text
kbHost = "https://rfp1.azurewebsites.net/********"
kbId = "********-********-*********"
endpointKey = "********-********-********"
'Loop through all non-blank cells
Dim answer, score As String
Dim myArray() As String
Dim obj As New DataObject
answer = GetAnswer(str, kbHost, kbId, endpointKey)
Call ClipBoard_SetData(answer)
End Sub
Function GetAnswer(question, kbHost, kbId, endpointKey) As String
'HTTP Request Settings
Dim qnaUrl As String
qnaUrl = kbHost & "/knowledgebases/" & kbId & "/generateAnswer"
Dim contentType As String
contentType = "application/json"
Dim data As String
data = "{""question"":""" & question & """}"
'Send Request
Dim xmlhttp As New MSXML2.XMLHTTP60
xmlhttp.Open "POST", qnaUrl, False
xmlhttp.setRequestHeader "Content-Type", contentType
xmlhttp.setRequestHeader "Authorization", "EndpointKey " & endpointKey
**xmlhttp.send data**
'Convert response to JSON
Dim json As Scripting.Dictionary
Set json = JsonConverter.ParseJson(xmlhttp.responseText)
Dim answer As Scripting.Dictionary
For Each answer In json("answers")
'Return response
GetAnswer = answer("answer")
Next
End Function
Private Function json_ParseObject(json_String As String, ByRef json_Index As Long) As Scripting.Dictionary
Dim json_Key As String
Dim json_NextChar As String
Set json_ParseObject = New Scripting.Dictionary
json_SkipSpaces json_String, json_Index
...
I am encountering the following error which I am uncertain how to resolve: "This method cannot be called after the send method has been called".
The error occurs on the line: xmlhttp.send data
The GitHub issue you linked kind of had the answer, but it's not complete. Here's what you do (from the VBA Dev Console in Word):
In Modules > JsonConverter
Go to Private Function json_ParseObject
Add Scripting. to Dictionary in two places:
from:
Private Function json_ParseObject(json_String As String, ByRef json_Index As Long) As Dictionary
to:
Private Function json_ParseObject(json_String As String, ByRef json_Index As Long) As Scripting.Dictionary
and from:
Set json_ParseObject = New Dictionary
to:
Set json_ParseObject = New Scripting.Dictionary
In GetAnswer():
Also change from:
Dim json As Dictionary
to:
Dim json As Scripting.Dictionary
and from:
Dim answer As Dictionary
to:
Dim answer As Scripting.Dictionary
Here's my full working code:
In ThisDocument:
Sub copyAnswer()
'User Settings
Dim kbHost As String, kbId As String, endpointKey As String
Dim str As String
str = "test"
kbHost = "https:/*********.azurewebsites.net/qnamaker"
kbId = "***************************"
endpointKey = "*************************"
'Loop through all non-blank cells
Dim answer, score As String
Dim myArray() As String
answer = GetAnswer(str, kbHost, kbId, endpointKey)
End Sub
Function GetAnswer(question, kbHost, kbId, endpointKey) As String
'HTTP Request Settings
Dim qnaUrl As String
qnaUrl = kbHost & "/knowledgebases/" & kbId & "/generateAnswer"
Dim contentType As String
contentType = "application/json"
Dim data As String
data = "{""question"":""" & question & """}"
'Send Request
Dim xmlhttp As New MSXML2.XMLHTTP60
xmlhttp.Open "POST", qnaUrl, False
xmlhttp.setRequestHeader "Content-Type", contentType
xmlhttp.setRequestHeader "Authorization", "EndpointKey " & endpointKey
xmlhttp.send data
'Convert response to JSON
Dim json As Scripting.Dictionary
Set json = JsonConverter.ParseJson(xmlhttp.responseText)
Dim answer As Scripting.Dictionary
For Each answer In json("answers")
'Return response
GetAnswer = answer("answer")
Next
End Function
In Modules > JsonConverter
Private Function json_ParseObject(json_String As String, ByRef json_Index As Long) As Scripting.Dictionary
Dim json_Key As String
Dim json_NextChar As String
Set json_ParseObject = New Scripting.Dictionary
json_SkipSpaces json_String, json_Index
If VBA.Mid$(json_String, json_Index, 1) <> "{" Then
Err.Raise 10001, "JSONConverter", json_ParseErrorMessage(json_String, json_Index, "Expecting '{'")
Else
json_Index = json_Index + 1
Do
json_SkipSpaces json_String, json_Index
If VBA.Mid$(json_String, json_Index, 1) = "}" Then
json_Index = json_Index + 1
Exit Function
ElseIf VBA.Mid$(json_String, json_Index, 1) = "," Then
json_Index = json_Index + 1
json_SkipSpaces json_String, json_Index
End If
json_Key = json_ParseKey(json_String, json_Index)
json_NextChar = json_Peek(json_String, json_Index)
If json_NextChar = "[" Or json_NextChar = "{" Then
Set json_ParseObject.Item(json_Key) = json_ParseValue(json_String, json_Index)
Else
json_ParseObject.Item(json_Key) = json_ParseValue(json_String, json_Index)
End If
Loop
End If
End Function
How do you replace the last occurance of a , with the word and? Can you please give me an idea?
i have 3 checkboxes, 1 rich textbox
to display the output, 1 button
(Aparri) or (Camalanuigan) or (Lallo)
Cagayan(Aparri, Camalanuigan) or Cagayan(Aparri,Camalanuigan,Lallo)
I would like the output to be like this: #Cagayan(Aparri and Camalanuigan) or #Cagayan(Aparri,Camalanuigan And Lallo)
this is my code:
Dim rws As String
If Aparri.Checked = True Then
close_parenthesis.Checked = True
If rws = "" Then
rws = "(" + Aparri.Text
End If
End If
If Aparri.Checked = False Then
rws = ""
End If
If Camalanuigan.Checked = True Then
close_parenthesis.Checked = True
If rws = "" Then
rws = "(" + Camalanuigan.Text
Else
rws = rws & ", " & Camalanuigan.Text
End If
End If
If Lallo.Checked = True Then
close_parenthesis.Checked = True
If rws = "" Then
rws = "(" + Lallo.Text
Else
rws = rws & ", " & Lallo.Text
End If
End If
If close_parenthesis.Checked = True Then
If rws = "" Then
Else
rws = rws + close_parenthesis.Text
End If
End If
Display.Text = rws.ToString
Output: (Aparri,Camalanuigan,Lallo)
i want the out like this (Aparri,Camalanuigan and Lallo)
Here, I haven't even seen your code but I get what you want to do by looking at the picture. It can be done in shorter version but I have explained what's going on in each and every line so it's lengthy.
I have written this code:
'let's say the string is "Aparri, Camalanuigan, Lallo" . that's what your code does, right?
dim Strng as string = "Aparri, Camalanuigan, Lallo"
'now find the position of last appearing ","
Dim comaposition As Integer
comaposition = Strng.LastIndexOf(",") 'it is zero based
'if not found, it will return -1 and u can exit, no need to do the work
if commaposition = "-1" then
exit sub
end if
'remove the comma
Dim String_After_Removing_Comma As String
String_After_Removing_Comma = Strng.Remove(comaposition, 1)
'add "and" in the same position where comma was found
Dim final_string As String
final_string = String_After_Removing_Comma.Insert(comaposition, " and")
'show it on the textbox
DisplayTxt.Text = final_string
You can do this thing after finding your final string (rws in your code).
Hope this helps
You can use the following function to replace last occurrence.
Public Function ReplaceLastOccurrence(ByVal source As String, ByVal searchText As String, ByVal replace As String) As String
Dim position = source.LastIndexOf(searchText)
If (position = -1) Then Return source
Dim result = source.Remove(position, searchText.Length).Insert(position, replace)
Return result
End Function
and you use display text as
Display.Text = ReplaceLastOccurence(rws, ",", "and")
in your last line of code
You always can do it by yourself with single loop and knowledge about last index
' Create array of selected strings
Dim selectedTexts =
New List(Of CheckBox) From { Aparri, Camalanuigan, Lallo }.
Where(Function(checkbox) checkbox.Checked).
Select(Function(checkbox) checkbox.Text).
ToArray()
' Separate selected strings by delimeters
Dim lastIndex = selectedTexts.GetUpperBound(0)
Dim builder = New StringBuilder()
For i As Integer = 0 To lastIndex
If i > 0 Then
Dim delimeter = If(lastIndex > 0 AndAlso lastIndex = i, " and ", ", ")
builder.Append(delimeter)
End If
builder.Append(test(i))
Next
' Wrap with parenthesis if result not empty
If builder.Length > 0 Then
builder.Insert(0, "(")
Dim close = If(close_parenthesis.Checked, close_parenthesis.Text, "")
builder.Append(close)
End If
' Print result
Display.Text = builder.ToString()
I want to split a string - which includes multiple lines - into new strings.
As it seems that people dont understand my problem here some further informations:
I read out values into strings from a XML-file. Some of those strings countain multiple lines. Now I need every single value of that string on a new string(variable) so that I can tell Homer to drink a beer and tell Lenny to go to bed and not tell the whole Team to go to bed. (Hopefully this story helps you :D )
To keep this simple I'll define a "static" string for this sample.
I'll put 3 of my tries down below. I'd love to hear what's wrong with them. I also tried it with lists and enums where I could split the string but no define a new one..
But I assume that there is a much easier solution for my problem...
Dim team As String = "Simpson, Homer" & vbCrLf & "Leonard, Lenny" & vbCrLf & "Carlson, Carl"
1.
Dim objReader As New StringReader(team)
Dim tm() As String
Dim i As Integer = 1
Do While objReader.Peek() <> -1
tm(i) = objReader.ReadLine() & vbNewLine
i = i + 1
Loop
Dim i As Integer = 0
For Each Line As String In team.Split(New [Char]() {CChar(vbTab)})
Dim tm(i) As String = ReadLine(team, i)
i = i + 1
Next
3.
Dim tm() As String
Dim i As Integer = 0
Dim objReader As New StringReader(team)
Do While objReader.Peek() <> -1
tm(i) = ReadLine(team, i)
i = i + 1
Loop
And the function used in 2. and 3.
Public Function ReadLine(ByVal sFile As String, Optional ByVal nLine As Long = 1) As String
Dim sLines() As String
Dim oFSO As Object
Dim oFile As Object
On Error GoTo ErrHandler
oFSO = CreateObject("Scripting.FileSystemObject")
If oFSO.FileExists(sFile) Then
oFile = oFSO.OpenTextFile(sFile)
sLines = Split(oFile.ReadAll, vbCrLf)
oFile.Close()
Select Case Math.Sign(nLine)
Case 1
ReadLine = sLines(nLine - 1)
Case -1
ReadLine = sLines(UBound(sLines) + nLine + 1)
End Select
End If
ErrHandler:
oFile = Nothing
oFSO = Nothing
End Function
Thanks in advance for any shared thoughts.
There is in fact an easy solution for my problem. Sorry if I caused confusion.
Module Module1
Dim team As String = "Simpson, Homer" & vbCrLf & "Leonard, Lenny" & vbCrLf & "Carlson, Carl"
Sub Main()
Dim tm As String() = team.Split(vbLf)
'Test
Console.WriteLine(tm(0)) 'Homer
Console.WriteLine(tm(1)) 'Lenny
Console.WriteLine(tm(2)) 'Carl
End Sub
End Module