Deleting words/strings containing a specific character in MS Access - ms-access

I'm writing a query to extract text that was entered through a vendor-created word processor to an Oracle database and I need to export it to Word or Excel. The text is entered into a memo field and the text is intertwined with codes that the word processor uses for different functions (bold, indent, hard return, font size, etc.).
I've used the replace function to parse out a lot of the more common codes, but there are so many variations, it's nearly impossible to catch them all. Is there a way to do this? Unfortunately, I'm limited to using Microsoft Access 2010 to try and accomplish this.
The common thread I've found is that all the codes start with a back-slash and I'd like to be able to delete all strings that start with a back-slash up to the next space so all the codes are stripped out of the final text.
Here's a brief example of the text I'm working with:
{\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl{\f0\fnil\fcharset0 Times New Roman;
\viewkind4\uc1\pard\f0\fs36 An abbreviated survey was conducted
on 02/02/15 to investigate complaint #OK000227. \par
No deficiencies were cited.\par
\fs20\par
}}

If your machine has Microsoft Word installed then you already have an RTF parser available so you don't have to "roll your own". You can just get Word to open the RTF document and save it as plain text like this:
Option Compare Database
Option Explicit
Public Function RtfToPlainText(rtfText As Variant) As Variant
Dim rtn As Variant
Dim tempFolder As String, rtfPath As String, txtPath As String
Dim fso As Object ' FileSystemObject
Dim f As Object ' TextStream
Dim wordApp As Object ' Word.Application
Dim wordDoc As Object ' Word.Document
Dim tempFileName As String
tempFileName = "~RtfToPlainText"
If IsNull(rtfText) Then
rtn = Null
Else
' save RTF text as file
Set fso = CreateObject("Scripting.FileSystemObject")
tempFolder = fso.GetSpecialFolder(2) ' Temporaryfolder
rtfPath = tempFolder & "\" & tempFileName & ".rtf"
Set f = fso.CreateTextFile(rtfPath)
f.Write rtfText
f.Close
Set f = Nothing
' open in Word and save as plain text
Set wordApp = CreateObject("Word.Application")
Set wordDoc = wordApp.Documents.Open(rtfPath)
txtPath = tempFolder & "\" & tempFileName & ".txt"
wordDoc.SaveAs2 txtPath, 2 ' wdFormatText
wordDoc.Close False
Set wordDoc = Nothing
wordApp.Quit False
Set wordApp = Nothing
fso.DeleteFile rtfPath
' retrieve plain text
Set f = fso.OpenTextFile(txtPath)
rtn = f.ReadAll
f.Close
Set f = Nothing
fso.DeleteFile txtPath
Set fso = Nothing
End If
RtfToPlainText = rtn
End Function
Then, if you had a table with two Memo fields - [rtfText] and [plainText] - you could extract the plain text into the second Memo field using the following query in Access:
UPDATE rtfTestTable SET plainText = RtfToPlainText([rtfText]);

The text you are working with is RTF. Here is a tutorial about the file format.
This link (on another site, registration required) may give you copy & paste code you can use to convert rtf fields to txt.
You may be able to copy the value of the field from the database and paste it into notepad and then save the notepad file as "test.rtf"...you could then double click the file icon and the document may open.
RTF is an old MS file format that allows formatting of text. See this wikipedia page.

Related

Convert RTF embedded OLE to HTML in Access in VBA

I've got a table that has an embedded OLE field that contains RichText formatted data. I need to transfer this data to MySQL database and convert it to HTML. I use Access. Is there a way to do it quickly in VBA?
I searched the web, most people use RichText control (richtx32.ocx) to get plain text, but I need it to remain formatted and I also don't have this control.
Here is how I solved my problem:
Option Explicit
Public wrd As Word.Application
Public doc As Word.Document
Function RTF2HTMLviaWord(rtf As String) As String
'Open Tools --> References --> and check Microsoft Scripting Runtime
Dim fso As New FileSystemObject
Dim text As TextStream
Dim temp As String
temp = Environ("TEMP")
If Len(rtf) > 1 Then
Set text = fso.CreateTextFile(temp & "\RTF2HTML.rtf", True)
text.Write rtf
text.Close
If wrd Is Nothing Then
Set wrd = New Word.Application
End If
Set doc = wrd.Documents.Open(temp & "\RTF2HTML.rtf", False)
doc.SaveAs temp & "\RTF2HTML.htm", wdFormatHTML
doc.Close
fso.DeleteFile temp & "\RTF2HTML.rtf"
Set text = fso.OpenTextFile(temp & "\RTF2HTML.htm", ForReading, False)
RTF2HTMLviaWord = text.ReadAll
text.Close
fso.DeleteFile temp & "\RTF2HTML.htm"
Else
RTF2HTMLviaWord = ""
End If
End Function
The only downside is that Word produces too many garbage HTML tags. I wish it could save minimal HTML tags without formatting.

Creating a button in Access to to open a word document

I have a word document that uses mail merge feature and gets its information from the access db. When I use this code it does not open the word document with the current information. It opens the word document with the last saved information.
If I open the word document on its own, from the task bar, it asks if I want to run the SQL and I click yes and everything operates normally. I want to click a button from within access to accomplish this same task to open the contract.
Here is the code I used:
Private Sub Command205_Click()
Dim LWordDoc As String
Dim oApp As Object
'Path to the word document
LWordDoc = "C:\Users\.....k Up\01- Proposal\contract.docx"
If Dir(LWordDoc) = "" Then
MsgBox "Document not found."
Else
'Create an instance of MS Word
Set oApp = CreateObject(Class:="Word.Application")
oApp.Visible = True
'Open the Document
oApp.Documents.Open FileName:=LWordDoc
End If
End Sub
***I should add that I am not a coder and know nothing about VBA, I copied this from this website so any help you can offer would be greatly appreciated. If you can provide me with coding or enough guidance to get me on the way would be great. Thank you
This code will run in Access to open a Mail Merge document and update content and save.
Using the link I originally posted (http://www.minnesotaithub.com/2015/11/automatic-mail-merge-with-vba-and-access/), I made a couple of modifications and was able to get that code to work.
I needed to add: ReadOnly:=True, _ to prevent a sharing violation
and I changed the Table Name of the source data.
NOTE!! You will need to change sode marked with'###' as follows:
###-1 Change to specify the full path of your TEMPLATE!!!
###-2 Change the SQLSTATEMENT to specify your recordsource!!!
Paste this code into your form, make sure you have a Command Button Click Event that executes (Either rename 'Command205' in this code, or change your control name).
Option Compare Database
Option Explicit
Private Sub Command205_Click()
Dim strWordDoc As String
'Path to the word document of the Mail Merge
'###-1 CHANGE THE FOLLOWING LINE TO POINT TO YOUR DOCUMENT!!
strWordDoc = "C:\Users\.....k Up\01- Proposal\contract.docx"
' Call the code to merge the latest info
startMerge strWordDoc
End Sub
'----------------------------------------------------
' Auto Mail Merge With VBA and Access (Early Binding)
'----------------------------------------------------
' NOTE: To use this code, you must reference
' The Microsoft Word 14.0 (or current version)
' Object Library by clicking menu Tools > References
' Check the box for:
' Microsoft Word 14.0 Object Library in Word 2010
' Microsoft Word 15.0 Object Library in Word 2013
' Click OK
'----------------------------------------------------
Function startMerge(strDocPath As String)
Dim oWord As Word.Application
Dim oWdoc As Word.Document
Dim wdInputName As String
Dim wdOutputName As String
Dim outFileName As String
' Set Template Path
wdInputName = strDocPath ' was CurrentProject.Path & "\mail_merge.docx"
' Create unique save filename with minutes and seconds to prevent overwrite
outFileName = "MailMergeFile_" & Format(Now(), "yyyymmddmms")
' Output File Path w/outFileName
wdOutputName = CurrentProject.Path & "\" & outFileName
Set oWord = New Word.Application
Set oWdoc = oWord.Documents.Open(wdInputName)
' Start mail merge
'###-2 CHANGE THE SQLSTATEMENT AS NEEDED
With oWdoc.MailMerge
.MainDocumentType = wdFormLetters
.OpenDataSource _
Name:=CurrentProject.FullName, _
ReadOnly:=True, _
AddToRecentFiles:=False, _
LinkToSource:=True, _
Connection:="QUERY mailmerge", _
SQLStatement:="SELECT * FROM [tblEmployee]" ' Change the table name or your query
.Destination = wdSendToNewDocument
.Execute Pause:=False
End With
' Hide Word During Merge
oWord.Visible = False
' Save file as PDF
' Uncomment the line below and comment out
' the line below "Save file as Word Document"
'------------------------------------------------
'oWord.ActiveDocument.SaveAs2 wdOutputName & ".pdf", 17
' Save file as Word Document
' ###-3 IF YOU DON'T WANT TO SAVE AS A NEW NAME, COMMENT OUT NEXT LINE
oWord.ActiveDocument.SaveAs2 wdOutputName & ".docx", 16
' SHOW THE DOCUMENT
oWord.Visible = True
' Close the template file
If oWord.Documents(1).FullName = strDocPath Then
oWord.Documents(1).Close savechanges:=False
ElseIf oWord.Documents(2).FullName = strDocPath Then
oWord.Documents(2).Close savechanges:=False
Else
MsgBox "Well, this should never happen! Only expected two documents to be open"
End If
' Quit Word to Save Memory
'oWord.Quit savechanges:=False
' Clean up memory
'------------------------------------------------
Set oWord = Nothing
Set oWdoc = Nothing
End Function

How to get rich text, which Access formats using HTML, into a Word doc

I am copying formatted text from a Word document into a rich text field in Access.
Later I want to use VBA to create a new Word document and write the text as formatted to it.
The problem is, Access saves rich text with HTML formatting. And when you try to write that to a doc or docx, you see the text and its HTML tags.
How do I write the text to a Word document so that it retains the intended formatting and doesn't show HTML codes?
The only way I have found that works (without modifying the input string) is to write the HTML to a temporary file, then use .InsertFile to load that file into the word document. Here's a sub that takes the input argument and puts it into a new Word document:
Sub WriteToWord(myHtmlFormattedText as String)
Dim objWord As Word.Application
Dim doc As Word.Document
Dim fso As Object ' FileSystemObject
Dim f As Object ' TextStream
Dim tempHtmlFile As String
' Write your HTML content to a temp file:
Set fso = CreateObject("Scripting.FileSystemObject")
tempHtmlFile = fso.GetSpecialFolder(2) & "\" & fso.GetTempName & ".htm"
Set f = fso.CreateTextFile(tempHtmlFile, True)
f.Write myHtmlFormattedText
f.Close
Set f = Nothing
Set fso = Nothing
' Set up word object
Set objWord = CreateObject("Word.Application")
With objWord
.Visible = True
Set doc = .Documents.Add
End With
'Add HTML file contents:
objWord.Selection.InsertFile tempHtmlFile
' Show the doc
doc.Activate
End Sub
Not sure this will help, but there are a few different pasting features in Microsoft Word (in thee upper left corner of the 'Home' tab) that many people overlook
This allows you to paste with/without formatting. Not sure if it will solve your specific issue, but hopefully!

How to copy the contents of an attached file from an MS Access DB into a VBA variable?

Background Information:
I am not very savvy with VBA, or Access for that matter, but I have a VBA script that creates a file (a KML to be specific, but this won't matter much for my question) on the users computer and writes to it using variables that link to records in the database. As such:
Dim MyDB As Database
Dim MyRS As Recordset
Dim QryOrTblDef As String
Dim TestFile As Integer
QryOrTblDef = "Table1"
Set MyDB = CurrentDb
Set MyRS = MyDB.OpenRecordset(QryOrTblDef)
TestFile = FreeFile
Open "C:\Testing.txt"
Print #TestFile, "Generic Stuff"
Print #TestFile, MyRS.Fields(0)
etc.
My Situation:
I have a very large string(a text document with a large list of polygon vertex coordinates) that I want to add to a variable to be printed to another file (a KML file, noted in the above example). I was hoping to add this text file containing coordinates as an attachment datatype to the Access database and copy its contents into a variable to be used in the above script.
My Question:
Is there a way I can access and copy the data from an attached text file (attached as an attachment data type within a field of an MS Access database) into a variable so that I can use it in a VBA script?
What I have found:
I am having trouble finidng information on this topic I think mainly because I do not have the knowledge of what keywords to be searching for, but I was able to find someones code on a forum, "ozgrid", that seems to be close to what I want to do. Though it is just pulling from a text file on disk rather than one attached to the database.
Code from above mentioned forum that creates a function to access data in a text file:
Sub Test()
Dim strText As String
strText = GetFileContent("C:\temp\x.txt")
MsgBox strText
End Sub
Function GetFileContent(Name As String) As String
Dim intUnit As Integer
On Error Goto ErrGetFileContent
intUnit = FreeFile
Open Name For Input As intUnit
GetFileContent = Input(LOF(intUnit), intUnit)
ErrGetFileContent:
Close intUnit
Exit Function
End Function
Any help here is appreciated. Thanks.
I am a little puzzled as to why a memo data type does not suit if you are storing pure text, or even a table for organized text. That being said, one way is to output to disk and read into a string.
''Ref: Windows Script Host Object Model
Dim fs As New FileSystemObject
Dim ts As TextStream
Dim rs As DAO.Recordset, rsA As DAO.Recordset
Dim sFilePath As String
Dim sFileText As String
sFilePath = "z:\docs\"
Set rs = CurrentDb.OpenRecordset("maintable")
Set rsA = rs.Fields("aAttachment").Value
''File exists
If Not fs.FileExists(sFilePath & rsA.Fields("FileName").Value) Then
''It will save with the existing FileName, but you can assign a new name
rsA.Fields("FileData").SaveToFile sFilePath
End If
Set ts = fs.OpenTextFile(sFilePath _
& rsA.Fields("FileName").Value, ForReading)
sFileText = ts.ReadAll
See also: http://msdn.microsoft.com/en-us/library/office/ff835669.aspx

How to write to a specific line in a text file using vb

I have a text file with this sample data
abduct test|1
chip test|2
hatter test|3
evil test|4
I would like to know how I could loop through it to find a user and remove that line.
This is what I have so far:
Public Sub RemoveMember(member As String)
Dim u As String, strdata() As String
Open (App.Path & "\Membership.txt") For input As #1
Do
input #1, u
strdata = Split(u, "|")
If strdata(0) = member Then
'figure out a way to remove this line from the text file'
End If
Loop Until EOF(1)
Close #1
End Sub
I would say:
Read in the lines one by one
Check if the line contains the member to be deleted
Write back the line to a new file if it does not
After reading all the lines delete the original file
Rename the new file to the original file
Stefan's method is probably faster but will use a lot of memory if the file grows very large.
I am not familiar wityh VB's native file method. Using FileSystemObject (reference Microsoft Scripting Host) you wil get:
Dim clsOriginalFile as TextStream
Dim clsNewFile as TextStream
Dim FSO as New FileSystemObject
Dim varLine as Variant
Dim strLine as String
set clsOriginalFile=FSO.OpenTextFile "members.txt", ForReading
set clsNewFile =FSO.OpentTextFile "temp.txt", ForWriting, True
Do While Not clsOriginalFile.AtEndOfStream
varLine = clsOriginalFile.ReadLine
strLine=varLine
If instr(strLine,member)=0 Then
clsNewFile.WriteLine strLine
End If
Loop
clsOriginalFile.Close
clsNewFile.Close
FSO.DeleteFile("members.txt")
FSO.MoveFile("temp.txt","members.txt")
Written without the help of the IDE, so there may a few typos in the code.