access vba get cyrillic text from ini file into database - ms-access

2012/08/31 : Updated my Post
searched all the web for it, found pieces but nothing really helped so i turn to you.
Information about environment:
Programming language is VBA / Access 2003
Data will be read from existing ".ini" File
Data should be inserted into Access Database
Now to my Problem:
I've got a ini file with information inside an ini file. The file looks something like this:
[product_details]
product_description=my product description
product_name=my product
product_price=11.0
product_sku=myproduct2012
these information are saved into "products.ini", when open in notepad or notepad++ it will be displayed correct and can be inserted into my access database and i can display these information in my form
but now someone wants to have something like this:
[product_details]
product_description=мое описание продукта
product_name=мой продукт
product_price=11.0
product_sku=произведение2012
when loading these information via GetINIValue the Value will be saved into Database as unreadable text.
edit: also in Notepad / Notepad++ it is displayed correct, so the cyrillic chars are transferred correct into the ini-file
I really tried many things (using UNICODE Version of GetINIValue, get Code of Char etc., check if Cyrillic text) nothing helped.
What it should do:
I need help to get the Value from this ini entry no matter what language (in this case, English, German, french, Russian are just enough)
Hope someone could help me.
Edit: I've tried Remou's Testing with this Peace of Code open it up by following:
Dim SQL As String
Dim strValue As String
strValue = GetValueOf("product_details","product_description","C:\cyrillic.txt")
SQL = "UPDATE [products] SET [product_description]='" & strValue & "' WHERE [product_id]=23;"
CurrentDb.Execute SQL,dbseechanges
Heres the Code of my Function to read out the Specific Line i need:
Public Function GetValueOf(ByVal Section As String, ByVal Entry As String, ByVal File As String)
Dim fs As New FileSystemObject
Dim ts As TextStream
Dim temp As String
Dim response As String
Dim intresponses As String
Dim SectionFoundBegin As Boolean
Dim SectionFoundEnd As Boolean
Dim DoNext As Boolean
Dim Parse() As String
Dim Finished As Boolean
SectionFoundBegin = False
SectionFoundEnd = False
Set ts = fs.OpenTextFile(File, ForReading, , TristateTrue)
response = ""
intresponses = 1
Finished = False
Do
DoNext = False
temp = ts.ReadLine
If (Not Finished) Then
If (temp = "[" & Section & "]") And Not DoNext Then
SectionFoundBegin = True
DoNext = True
End If
If ((InStr(1, temp, "[") > 0) And (SectionFoundBegin)) And Not DoNext Then
SectionFoundEnd = True
DoNext = True
End If
If (SectionFoundBegin And Not SectionFoundEnd) And Not DoNext Then
If (InStr(1, temp, "=") > 0) Then
Parse = Split(temp, "=")
If (Parse(0) = Entry) Then
While (intresponses <= UBound(Parse))
response = response + Parse(intresponses)
intresponses = intresponses + 1
Wend
DoNext = True
Else
DoNext = True
End If
Else
DoNext = True
End If
End If
End If
Loop Until ts.AtEndOfStream
GetValueOf = response
End Function
What i need:
Something like:
"UPDATE [products] SET [product_description]='мое описание продукта' WHERE [product_id]=23;"
What i get:
"UPDATE [products] SET [product_description]='??? ???????? ????????' WHERE [product_id]=23;"
UPDATE:
Well now i really your help:
I've inserted the following Code:
Public Function GetUnicodeValueOf(ByVal Section As String, ByVal Entry As String, ByVal File As String)
Dim fs As Object
Dim ts As Object
Set fs = CreateObject("Scripting.FileSystemObject")
Dim temp As String
Dim strResponse As String
Dim intResponses As Integer
Dim SectionFoundBegin As Boolean
Dim SectionFoundEnd As Boolean
Dim DoNext As Boolean
Dim Parse() As String
Dim Finished As Boolean
On Error GoTo Error_GetUnicodeValueOf
SectionFoundBegin = False
SectionFoundEnd = False
Set ts = fs.OpenTextFile(File, ForReading, , TristateTrue)
strResponse = ""
intResponses = 1
Finished = False
Do
DoNext = False
temp = ts.ReadLine
If (Not Finished) Then
If (temp = "[" & Section & "]") And Not DoNext Then
SectionFoundBegin = True
DoNext = True
End If
If ((InStr(1, temp, "[") > 0) And (SectionFoundBegin)) And Not DoNext Then
SectionFoundEnd = True
DoNext = True
End If
If (SectionFoundBegin And Not SectionFoundEnd) And Not DoNext Then
If (InStr(1, temp, "=") > 0) Then
Parse = Split(temp, "=")
If (Parse(0) = Entry) Then
While (intResponses <= UBound(Parse))
strResponse = strResponse + Parse(intResponses)
intResponses = intResponses + 1
Finished = True
Wend
DoNext = True
Else
DoNext = True
End If
Else
DoNext = True
End If
End If
End If
Loop Until ts.AtEndOfStream
Exit_GetUnicodeValueOf:
GetUnicodeValueOf = strResponse
Exit Function
Error_GetUnicodeValueOf:
ActionLogging "Fehler beim Parsen der Datei '" & File & "'"
Resume Exit_GetUnicodeValueOf
End Function
by using this file (saved as UTF-8 without BOM) on my Harddisc:
[product_details]
manufacturer_name=
product_id=50
sku=BU-01722
set=4
type=simple
type_id=simple
color=11
ean=
name=Колесникова
description=[LANGTEXT] Колесникова Е.В Я считаю до двадцати [Рабочая тетрадь] 6-7л
short_description=[KURZTEXT] Колесникова Е.В
old_id=
weight=1.0000
news_from_date=
news_to_date=
status=1
url_key=kolesnikova
url_path=kolesnikova.html
visibility=4
gift_message_available=2
required_options=0
has_options=0
image_label=
small_image_label=
thumbnail_label=
created_at=2012-06-25 07:58:29
updated_at=2012-07-27 09:06:24
price=2.0000
special_price=
special_from_date=
special_to_date=
cost=
tax_class_id=2
minimal_price=
enable_googlecheckout=1
meta_title=
meta_keyword=
meta_description=
is_recurring=0
recurring_profile=
custom_design=
custom_design_from=
custom_design_to=
custom_layout_update=
page_layout=
options_container=container2
and i need to have:
[LANGTEXT] Колесникова Е.В Я считаю до двадцати [Рабочая тетрадь] 6-7л
from INI-Key: description
into my access database.
First it works as it should but now when i'm loading a file that is saved with "TriStateTrue"
everything ends up in : ?????????????????????????????????????????????
in one line.
With TriStateMixed, everything is parsed well except of the cyrillic text which comes like
КолеÑникова Е.Ð’ Я Ñчитаю до двадцати [Ð Ð°Ð±Ð¾Ñ‡Ð°Ñ Ñ‚ÐµÑ‚Ñ€Ð°Ð´ÑŒ] 6-7л
i searched the sourcecode and didn't found the error.
FILE is UTF-8 without BOM (coming from selfwritten Web API for Magento)
Using Access 2003
Need to get Cyrillic Text into my Database where also German / English Texts could be inside the File

Long time ago, i asked this Question and finally got the answer, but because of the lack of time i didn't managed to "Answer myself" here and for other who might have these problems.
First of all, about the Read-Problem:
The Edit from my Question with TryStateTrue was the Right answer, this was the correct line which was needed to load
But now there's the Catch:
The Rules in VBA(6 or lower) are simple:
What will be saved in an String will be stored as ASCII Value. So every Char which is not an ASCII Code will be thrown away and saved as "?"
How did i managed to save those Data?
I Managed to save those Data by using an selfwritten Tool in C# (.NET) which can Handle UTF-8 Strings and can Connect to the Database.
Save Section + Key in List or set as Executable Parameters and where you will "UPDATE" the Value
e.g.:
[product_details]\name;productsTableName;productsNameField;IdentKeyField;IdentKeyValue
open Executable with Arguments or without and load the List
Connect to the desired Access-Database
Read the Section\Key-Value and Send to the Database directly by UPDATE-STATEMENT
e.g:
"UPDATE [productsTableName] SET [productsNameField]='" + ValueFromSectionKey + "' WHERE [IdentKeyField]=IdentKeyValue
Disconnect Database
Close Program
The Result:
a little bit slower at first because writing down what Huge List of Informations
also Writing down everything inside the Database, also with Errors (?????? instead of считаю) secures that if your file is ASCII-"readable" you didn't forget anything
beautiful UTF-8-Encoded and Readable Text inside an Access 2003 Database
The Pros about this Method
outsourced and expendable Tool, when written correctly it can be used for other projects too
understanable Code in Access (you write down informations, and after everything was listed you open up a Program which process these)
very fast when optimized (read the Length and split the list into multiple workers which update the database simultanously)
The Cons about this Method
outsourced
no possibility to save directly into a variable inside VBA(6 or lower)
external tool could be blocked by firewall
before "updating" Database there is unreadable Text inside the Database
more Update-Calls on Database as directly
user-typos inside list or Text containing the delimiter may let the UPDATE statement fail.
Hope i could help.

Related

Check permission of the directory in VBA Access before creating folder

I'm trying to implement a certain feature in the Microsoft Access Database using VBA, so when a certain button is pressed, it will check first the availability of the folder in a server. If the folder doesn't exist, the corresponding folder will be created. However, the folders have permissions attached to them, which means only certain users can access it, and hence only certain users should create / access the folder. I have tried the following:
on error resume next
If Dir("Server/Data/Celes", vbDirectory) = "Celes" Then
Else
MkDir ("Server/Data/Celes")
End If
But I'm not sure if it's the best way to handle this problem. I use the "On Error Resume Next", so that if the error occurs due to the lack of permission to the folder (that already exists), it will ignore it. What are some better ways to handle this? Thank you.
I also have checked the following links:
https://social.msdn.microsoft.com/Forums/office/en-US/a79054cb-52cf-48fd-955b-aa38fd18dc1f/vba-verify-if-user-has-permission-to-directory-before-saveas-attempt?forum=exceldev
Check Folder Permissions Before Save VBA
but both of them concerns with saving the file, not creating folder.
After several days without success, finally I found the solution:
Private function canAccess(path as string) as boolean
Dim oShell As Object
Set oShell = CreateObject("WScript.Shell")
Dim result As Integer
Dim command As String
command = "icacls " & """" & pfad & """"
result = oShell.Run(command, 0, True)
'Check privilege; file can be accessed if error code is 0.
'Else, errors are encountered, and error code > 0.
If result <> 5 and result <> 6 Then
KannAufDateiZugreifen = True
Else
KannAufDateiZugreifen = False
End If
end function
private sub button_click()
if canAccess ("Server/Data/Celes") then
If Dir("Server/Data/Celes", vbDirectory) = "Celes" Then
Else
MkDir ("Server/Data/Celes")
end if
End If
end sub
The function "canAccess" will simulate the running of the Windows shell, and execute "icacls" to see if the file can be accessed or not. If the function returns true, it means the "icacls" command is successful, which means the folder can be accessed. Otherwise, the file / folder can not be accessed.
I'm pretty sure this can be improved, but for now, it works.
I use the below function that recursively creates the full path (if required) and returns a value indicating success or failure. It works also with UNCs.
Private Function CreateFolder(ByVal sPath As String) As Boolean
'by Patrick Honorez - www.idevlop.com
'checks for existence of a folder and create it at once, if required
'returns False if folder does not exist and could NOT be created, True otherwise
'sample usage: If CreateFolder("C:\toto\test\test") Then debug.print "OK"
'updated 20130422 to handle UNC paths correctly ("\\MyServer\MyShare\MyFolder")
Dim fs As Object
Dim FolderArray
Dim Folder As String, i As Integer, sShare As String
If Right(sPath, 1) = "\" Then sPath = Left(sPath, Len(sPath) - 1)
Set fs = CreateObject("Scripting.FileSystemObject")
'UNC path ? change 3 "\" into 3 "#"
If sPath Like "\\*\*" Then
sPath = Replace(sPath, "\", "#", 1, 3)
End If
'now split
FolderArray = Split(sPath, "\")
'then set back the # into \ in item 0 of array
FolderArray(0) = Replace(FolderArray(0), "#", "\", 1, 3)
On Error GoTo hell
'start from root to end, creating what needs to be
For i = 0 To UBound(FolderArray) Step 1
Folder = Folder & FolderArray(i) & "\"
If Not fs.FolderExists(Folder) Then
fs.CreateFolder (Folder)
End If
Next
CreateFolder = True
hell:
End Function
'Must set a Reference to the Microsoft Scripting Runtime
Dim fso As FileSystemObject
Dim fil As File
Set fso = New Scripting.FileSystemObject
If fso.FileExists("\\serverName\folderName\fileName.txt") Then
'code execution here
Else
MsgBox "File and/or Path cannot be found", vbCritical, "File Not Found"
End If

Export all tables to txt files with export specification

I have a Access DB containing several different tables, each with a different structure (number & names of fields, number of rows, title).
What I would like to do is to export all these tables into txt files, with a given separator ("|"), point as decimal separator, quotes for strings.
I have browsed the internet and what I got was:
use DoCmd.TransferText acExportDelim command
save a customized export specification and apply it
I get an error messagge ("object does not exist") and I think it is related to the fact that the export specification is "sheet-specific", i.e. does not apply to tables with different fields and fieldnames.
Can you help me?
thanks!!
EDIT.
I post also the original code I run. As I said before, I am new to VBA, so I just looked for a code on the web, adapted it to my needs, and run.
Public Sub ExportDatabaseObjects()
On Error GoTo Err_ExportDatabaseObjects
Dim db As Database
Dim db As DAO.Database
Dim td As TableDef
Dim sExportLocation As String
Dim a As Long
Set db = CurrentDb()
sExportLocation = "C:\" 'Do not forget the closing back slash! ie: C:\Temp\
For a = 0 To db.TableDefs.Count - 1
If Not (db.TableDefs(a).Name Like "MSys*") Then
DoCmd.TransferText acExportDelim, "Export_specs", db.TableDefs(a).Name, sExportLocation & db.TableDefs(a).Name & ".txt", True
End If
Next a
Set db = Nothing
MsgBox "All database objects have been exported as a text file to " & sExportLocation, vbInformation
Exit_ExportDatabaseObjects:
Exit Sub
Err_ExportDatabaseObjects:
MsgBox Err.Number & " - " & Err.Description
Resume Exit_ExportDatabaseObjects
End Sub
Before running the code, I manually exported the first table saving the Export_specs to a file.
Consider a db with two tables, A and B.
When I run the code A is properly exported, then I get the following errore message "3011 - The Microsoft Access database engine could not find the object 'B#txt'. Make sure the object exists and that you spell its name and the path name correctly. If 'B#txt' is not a local object, check your network connection or contact the server administration".
So, it's kind of complex. I've created a routine that imports files using ImportExport Specs, you should be able to easily adapt to your purpose. The basic operation is to create a spec that does exactly what you want to one file. Then, export this spec using this code:
Public Function SaveSpecAsXMltoTempDirectory(sSpecName As String)
Dim oFSO As FileSystemObject
Dim oTS As TextStream
Set oFSO = New FileSystemObject
Set oTS = oFSO.CreateTextFile("C:\Temp\" & sSpecName & ".xml", True)
oTS.Write CurrentProject.ImportExportSpecifications(sSpecName).XML
oTS.Close
Set oTS = Nothing
Set oFSO = Nothing
End Function
Then open this file in Notepad and replace the file name with some placeholder (I used "FILE_PATH_AND_NAME" in this sample). Then, import back into database using this code:
Public Function SaveSpecFromXMLinTempDirectory(sSpecName As String)
Dim oFSO As FileSystemObject
Dim oTS As TextStream
Dim sSpecXML As String
Dim oSpec As ImportExportSpecification
Set oFSO = New FileSystemObject
Set oTS = oFSO.OpenTextFile("C:\Temp\" & sSpecName & ".xml", ForReading)
sSpecXML = oTS.ReadAll
For Each oSpec In CurrentProject.ImportExportSpecifications
If oSpec.Name = sSpecName Then oSpec.Delete
Next oSpec
Set oSpec = CurrentProject.ImportExportSpecifications.Add(sSpecName, sSpecXML)
Set oSpec = Nothing
oTS.Close
Set oTS = Nothing
Set oFSO = Nothing
End Function
Now you can cycle thru the files and replace the placeholder in the spec with the filename then execute it using this code:
Public Function ImportFileUsingSpecification(sSpecName As String, sFile As String) As Boolean
Dim oSpec As ImportExportSpecification
Dim sSpecXML As String
Dim bReturn As Boolean
'initialize return variable as bad until function completes
bReturn = False
'export data using saved Spec
' first make sure no temp spec left by accident
For Each oSpec In CurrentProject.ImportExportSpecifications
If oSpec.Name = "Temp" Then oSpec.Delete
Next oSpec
sSpecXML = CurrentProject.ImportExportSpecifications(sSpecName).XML
If Not Len(sSpecXML) = 0 Then
sSpecXML = Replace(sSpecXML, "FILE_PATH_AND_NAME", sFile)
'now create temp spec to use, get template text and replace file path and name
Set oSpec = CurrentProject.ImportExportSpecifications.Add("Temp", sSpecXML)
oSpec.Execute
bReturn = True
Else
MsgBox "Could not locate correct specification to import that file!", vbCritical, "NOTIFY ADMIN"
GoTo ExitImport
End If
ExitImport:
On Error Resume Next
ImportFileUsingSpecification = bReturn
Set oSpec = Nothing
Exit Function
End Function
Obviously you'll need to find the table name in the spec XML and use a placeholder on it as well. Let me know if you can't get it to work and i'll update for export.

Mail Merge from Access - Save Merged Document

I am attempting to open a document from access, execute a mail merge, and then save the document output from the merge using VBA.
Here is my current attempt:
Dim templateName as String, tempRoot as String
tempRoot = "C:\report\"
templateName = tempRoot & "template.doc"
Dim objDoc As Word.Document
Dim objWord As New Word.Application
Set objDoc = objWord.Documents.Open(templateName)
objWord.Visible = True
exportData "AnnualData", tempRoot & "annualData.txt" 'Outputs query to txt file for merge
objDoc.MailMerge.OpenDataSource NAME:= _
tempRoot & "annualData.txt", ConfirmConversions:=False, ReadOnly _
:=False, LinkToSource:=True, AddToRecentFiles:=False, PasswordDocument:= _
"", PasswordTemplate:="", WritePasswordDocument:="", _
WritePasswordTemplate:="", Revert:=False, Format:=wdOpenFormatAuto, _
Connection:="", SQLStatement:="", SQLStatement1:="", SubType:= _
wdMergeSubTypeOther
objDoc.MailMerge.Execute
objDoc.Close False 'Ideally after closing, the new document becomes the active document?
ActiveDocument.SaveAs tempRoot & "testReport.doc" 'And then save?
Set objWord = Nothing
Set objDoc = Nothing
I get the merged document, however, I am unable to save it. I receive an error stating that the command cannot be performed when no document is open.
If anyone can provide any suggestions, it would be appreciated.
Changed ActiveDocument to objWord.ActiveDocument. Ended up with the desired results.
Thanks Remou.
I just went through this. Here's what I'm doing and it works well. oDocument is the merge form that the user selects via an open dialog box. The excel file is the query that I've previously exported and stuck in the users temp folder. I tried this technique with Access queries and temp tables, but found that using excel was much more trouble free.
The Sleep command is from an imported system dll function ( Public Declare Sub Sleep Lib "kernel32" (ByVal dwMS As Long) ) and gives Word time to run the merge. Actually, that may be all you need. This is using Office 2007.
If Not oDocument Is Nothing Then
' get merge source file
Set oFSO = New FileSystemObject
Set oFolder = oFSO.GetSpecialFolder(TemporaryFolder)
strTempFile = oFolder.Path & "\PTDMergeSource.xls"
' run merge
With oDocument.MailMerge
.MainDocumentType = wdFormLetters
.Destination = wdSendToNewDocument
.OpenDataSource strTempFile, WdOpenFormat.wdOpenFormatDocument, False, False, False, False, , , , , , , "SELECT * FROM `tblMerge$`", , False, WdMergeSubType.wdMergeSubTypeAccess
.Execute True
End With
Sleep 2
oDocument.Close False
Else
MsgBox "Action was cancelled, or there was an error opening that document. Please try again, then try opening that document in Word. It may be someone else has locked that document (they are editing it). If the problem persists, email the document to the support contractor."
End If

"User-defined type not defined" for Excel Range Using Late Binding In Access 2003

I am trying to write a VBA script which imports all of the Excel files in a folder into a table in Access 2003, first checking if they have been imported or not. That part is fine. The issue I run into is clearing out some of the formulas that don't get used on the spreadsheet which causes difficulty when Access tries to import the range. when running the code as-is, I get an error "User-defined type not defined".
I am using late binding since I am developing for a site that uses multiple versions of Office and therfore can't reference the same library using early binding. The problem code is below:
Private Sub Command2_Click()
'Declare Variables
Dim xlApp As Object
Dim xlBook As Object
Dim LSQL As String
Dim SkippedCounter As Integer
Dim ImportedCounter As Integer
Dim BUN As Long
Dim SubmitDate As Date
Dim LSQL2 As String
Dim LSQL3 As String
'Start counters for final notice
SkippedCounter = 0
ImportedCounter = 0
Dim myDir As String, fn As String
'Set directory for importing files
myDir = "U:\Five Star\Operations\restore\Surveys\My InnerView - 2010\Action plans\Action plans - input for DB\"
'Function for selecting files in folder
fn = Dir(myDir & "*.xls")
'Determine if there are files in side the folder
If fn = "" Then
MsgBox "Folder is Empty!"
Else
'Begin cycling through files in the folder
Do While fn <> ""
'Create new Excel Object
Set xlApp = CreateObject("Excel.Application")
'Make it appear on the screen while importing
xlApp.Visible = True
'Open the workbook at hand
Set xlBook = xlApp.Workbooks.Open(myDir & fn)
'Check to see if it has been imported already
If xlBook.Sheets("Action plan form").Range("A1").Value = "Imported" Then
'If it has been imported, add 1 to the counter, close the file and close the instance of Excel
SkippedCounter = SkippedCounter + 1
xlBook.Close
xlApp.Quit
Set xlBook = Nothing
Set xlApp = Nothing
Else
'Otherwise, unprotect the worksheet
xlBook.UnProtect Password:="2010"
Dim c As Range
'Unhide worksheet needed and clean it up
xlBook.Sheets("Action plan DB data").Visible = True
xlBook.Sheets("Action plan DB data").Range("B10:O10").ClearFormats
xlBook.Sheets("Action plan DB data").Range("N11:N84").ClearFormats
For Each c In xlBook.Sheets("Action plan DB data").Range("DB_import")
If c.Value = "" Or c.Value = 0 Then c.Clear
Next c
...
The rest of the code should run fine, it jsut has an issue with the declaration of "range" and looping through it. Thanks for your help!
Remove As Range from Dim c As Range and that will make c into an object. That way when it gets late-bound to a range you won't have any issues.

Replace Module Text in MS Access using VBA

How do I do a search and replace of text within a module in Access from another module in access? I could not find this on Google.
FYI, I figured out how to delete a module programatically:
Call DoCmd.DeleteObject(acModule, modBase64)
I assume you mean how to do this programatically (otherwise it's just ctrl-h). Unless this is being done in the context of a VBE Add-In, it is rarely (if ever) a good idea. Self modifying code is often flagged by AV software an although access will let you do it, it's not really robust enough to handle it, and can lead to corruption problems etc. In addition, if you go with self modifying code you are preventing yourself from ever being able to use an MDE or even a project password. In other words, you will never be able to protect your code. It might be better if you let us know what problem you are trying to solve with self modifying code and see if a more reliable solution could be found.
After a lot of searching I found this code:
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'Function to Search for a String in a Code Module. It will return True if it is found and
'False if it is not. It has an optional parameter (NewString) that will allow you to
'replace the found text with the NewString. If NewString is not included in the call
'to the function, the function will only find the string not replace it.
'
'Created by Joe Kendall 02/07/2003
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Public Function SearchOrReplace(ByVal ModuleName As String, ByVal StringToFind As String, _
Optional ByVal NewString, Optional ByVal FindWholeWord = False, _
Optional ByVal MatchCase = False, Optional ByVal PatternSearch = False) As Boolean
Dim mdl As Module
Dim lSLine As Long
Dim lELine As Long
Dim lSCol As Long
Dim lECol As Long
Dim sLine As String
Dim lLineLen As Long
Dim lBefore As Long
Dim lAfter As Long
Dim sLeft As String
Dim sRight As String
Dim sNewLine As String
Set mdl = Modules(ModuleName)
If mdl.Find(StringToFind, lSLine, lSCol, lELine, lECol, FindWholeWord, _
MatchCase, PatternSearch) = True Then
If IsMissing(NewString) = False Then
' Store text of line containing string.
sLine = mdl.Lines(lSLine, Abs(lELine - lSLine) + 1)
' Determine length of line.
lLineLen = Len(sLine)
' Determine number of characters preceding search text.
lBefore = lSCol - 1
' Determine number of characters following search text.
lAfter = lLineLen - CInt(lECol - 1)
' Store characters to left of search text.
sLeft = Left$(sLine, lBefore)
' Store characters to right of search text.
sRight = Right$(sLine, lAfter)
' Construct string with replacement text.
sNewLine = sLeft & NewString & sRight
' Replace original line.
mdl.ReplaceLine lSLine, sNewLine
End If
SearchOrReplace = True
Else
SearchOrReplace = False
End If
Set mdl = Nothing
End Function
Check out the VBA object browser for the Access library. Under the Module object you can search the Module text as well as make replacements. Here is an simple example:
In Module1
Sub MyFirstSub()
MsgBox "This is a test"
End Sub
In Module2
Sub ChangeTextSub()
Dim i As Integer
With Application.Modules("Module1")
For i = 1 To .CountOfLines
If InStr(.Lines(i, 1), "This is a Test") > 0 Then
.ReplaceLine i, "Msgbox ""It worked!"""
End If
Next i
End With
End Sub
After running ChangeTextSub, MyFirstSub should read
Sub MyFirstSub()
MsgBox "It worked!"
End Sub
It's a pretty simple search but hopefully that can get you going.
additional for the function (looping through all the lines)
Public Function ReplaceWithLine(modulename As String, StringToFind As String, NewString As String)
Dim mdl As Module
Set mdl = Modules(modulename)
For x = 0 To mdl.CountOfLines
Call SearchOrReplace(modulename, StringToFind, NewString)
Next x
Set mdl = Nothing
End Function
Enjoy ^^