Writing one file with two functions in vba - vba

This is the header of my main function to write excel cells to an XML file. I want this to call another function, which can do its own set of writing.
Public Sub WriteXML()
Dim Sheet As Worksheet
Dim Cell As Range
Dim xmlFile
xmlFile = ThisWorkbook.Path & "\" & 'Test1' & ".xml"
Set Sheet = ActiveWorkbook.Worksheets("Sht1")
Open xmlFile For Output As #1
Print #1, "<?xml version=" & Chr(34) & "1.0" & Chr(34) & _
" encoding=" & Chr(34) & "UTF-8" & Chr(34) & "?>"
Call WriteCustomer(xmlFile)
This is the start of the second function, though I'm getting an 'object not found' sort of error.
Sub WriteCustomer(x As Variant)
Print x, " <Customer>"
Print x, " <First>" & 'Bill' & "</First>"
Print x, " <Last>" & 'Johnson' & "</Last>"
Print x, " </Customer>"
Print x, ""
End Sub
How do I need to construct the call and/or variable to pass the open file as an object to the second function?

You can request, store and pass around a handle as follows:
Dim handle As Integer
handle = FreeFile()
Open xmlFile For Output As #handle
Print #handle, "<?xml version=" & Chr(34) & "1.0" & Chr(34) & _
...
Call WriteCustomer(handle)
And
Sub WriteCustomer(handle As Integer)
Print #handle, " <Customer>"

Since you have opened the file in the first function with the line
Open xmlFile For Output As #1
Any code that references #1 while it's open will write to the same file. Thus you can simply rewrite your second function as
Sub WriteCustomer()
Print #1, " <Customer>"
Print #1, " <First>" & 'Bill' & "</First>"
Print #1, " <Last>" & 'Johnson' & "</Last>"
Print #1, " </Customer>"
Print #1, ""
End Sub

Related

Writing large amounts of data to a csv file

I couldn't find anything specific to this so here goes.
I have a For Each loop where I want to write values to a csv file. Currently, I use a WriteToFile function:
Public Sub WriteToFile(stuff as string, morestuff as string, moremorestuff as string))
Dim strFile As String = "\\SomeServer\somefilepath\WriteTo.csv"
Try
If System.IO.File.Exists(strFile) = True Then
'rename with startdate and enddate. Always want to create new
Dim objWriter As New System.IO.StreamWriter(strFile, True)
objWriter.WriteLine(Stuff & "," & MoreStuff & "," & Moremorestuff)
objWriter.Close()
Else
Dim writeFile As IO.StreamWriter
writeFile = IO.File.CreateText(strFile)
writeFile.WriteLine("Stuff" & "," & "MoreStuff" & "," & "MoreMoreStuff")
writeFile.WriteLine(Stuff & "," & MoreStuff & "," & MoreMoreStuff)
writeFile.Close()
End If
Catch ex As Exception
MessageBox.Show("An error has occured in the WriteToFile subroutine: " & ex.ToString) ' & vbCrLf & strPlugin & vbCrLf & strVersion)
End Try
End Sub
Rather than closing the StreamWriter after every record is written, is there a way to keep it open? Or should it be kept open?
I made some changes and came up with this. However, using this code, how would I create a header in the csv file?
If cur.Count > 0 Then
Using writer As System.IO.StreamWriter = New IO.StreamWriter("C:\Temp\UWConditions.csv")
For Each lrdata As LoanReportData In cur
loan = session.Loans.Open(lrdata.Guid)
If Not IsNothing(loan) Then
For Each condition As UnderwritingCondition In loan.Log.UnderwritingConditions
Title = condition.Title.Replace(",", "")
Desc = condition.Description.Replace(",", "")
UWName = loan.Session.Users.GetUser(loan.Fields("UWID").Value).FullName.Replace(",", "")
writer.WriteLine(lrdata("Loan.LoanNumber") & "," & Title & "," & Desc & "," & UWName)
Next
loan.Close()
End If
Next
End Using
End If

MS Access VBA Open a Text file and write to a specific line without overwriting the file

I have a text file that I would like to add a header and a footer to. I don't want to overwrite the first or last lines, rather I'd like to add a new first line and append a line to the end of the file.
The below Function works for appending to the bottom of the file but I'd like to be able to control where the line is inserted. Thank you!
Function WriteToText(sFile As String, sText As String)
On Error GoTo Err_Handler
Dim iFileNumber As Integer
iFileNumber = FreeFile ' Get unused file number
Open sFile For Append As #iFileNumber ' Connect to the file
Print #iFileNumber, sText ' Append our string
Close #iFileNumber ' Close the file Exit_Err_Handler:
Exit Function Err_Handler:
MsgBox "The following error has occured" & vbCrLf & vbCrLf & _
"Error Number: " & Err.Number & vbCrLf & _
"Error Source: Txt_Append" & vbCrLf & _
"Error Description: " & Err.Description & _
Switch(Erl = 0, "", Erl <> 0, vbCrLf & "Line No: " & Erl) _
, vbOKOnly + vbCritical, "An Error has Occured!"
GoTo Exit_Err_Handler End Function
What you do for a task like this:
Read the whole file into a string (Open For Input)
Add the data you want: S = "header line" & vbCrLf & S & vbCrLf & "footer line"
Write the whole string to the file, overwriting it (Open For Output)

Ms Access Get filename with wildcards or loop

I am using MS Access Forms and I am trying to open a file but don't know how to open the file based knowing only part of the name. Example below works
Private Sub Open_Email_Click()
On Error GoTo Err_cmdExplore_Click
Dim x As Long
Dim strFileName As String
strFileName = "C:\data\office\policy num\20180926 S Sales 112.32.msg"
strApp = """C:\Program Files\Microsoft Office\Office15\Outlook.exe"""
If InStr(strFileName, " ") > 0 Then strFileName = """" & strFileName & """"
x = Shell(strApp & " /f " & strFileName)
Exit_cmdExplore_Click:
Exit Sub
Err_cmdExplore_Click:
MsgBox Err.Description
Resume Exit_cmdExplore_Click
End Sub
If I change the strFilename to being
strFileName = "C:\data\" & Me.Office & "\" & Me.nm & " " & Me.pol & "\" & "*"& " S Sales " & Me.amt & "*" & ".msg"
It includes the * rather than using it as a wildcard, the date/numbers can be anything or in another format but always eight numbers. I tried using a while loop on the numbers but I am not sure the best way of doing this sorry.
You can use the Dir function to iterate over all files that match a string pattern.
strApp = """C:\Program Files\Microsoft Office\Office15\Outlook.exe"""
Dim strFilePattern As String
strFilePattern ="C:\data\" & Me.Office & "\" & Me.nm & " " & Me.pol & "\" & "*"& " S Sales " & Me.amt & "*" & ".msg"
Dim strFileName As String
strFileName = Dir(strFilePattern)
Do While Not strFileName = vbNullString
If InStr(strFileName, " ") > 0 Then strFileName = """" & strFileName & """"
x = Shell(strApp & " /f " & strFileName)
strFileName = Dir
Loop
The first call to Dir with the pattern as a parameter will find the first file that matches the pattern supplied. All subsequent calls without the pattern will return the next file that matches the pattern.
So, lets rebuild the question a bit. Imagine that you are having the following 5 files in a given folder:
A:\peter.msg
A:\bstack.msg
A:\coverflow.msg
A:\heter.msg
A:\beter.msg
and you need to find the files, that correspond to "A:\*eter.msg" and print them.
For this, you need to use the keyword Like:
Sub TestMe()
Dim someNames As Variant
someNames = Array("A:\peter.msg", "A:\bstack.msg", _
"A:\coverflow.msg", "A:\heter.msg", "A:\beter.msg")
Dim cnt As Long
For cnt = LBound(someNames) To UBound(someNames)
If someNames(cnt) Like "A:\*eter.msg" Then
Debug.Print someNames(cnt)
End If
Next
End Sub
Loop through files in a folder using VBA?

Optical Character Recognition from Access via VBA

I wish to OCR a few JPEGs (I can convert on the fly with iview).
I get:
Method 'OCR' of object 'IImage' failed
My code isn't perfect yet as I am focused on getting the .ocr method to function.
The images are photos and contain only a few characters. I could use a barcode reader, but those are hard to find free.
Public Function OCRtest(strTempImg)
pXname = "ocrTest"
On Error GoTo err_hand
Dim miDoc As Object
Dim miWord As MODI.Word
Dim strWordInfo As String
Set miDoc = CreateObject("MODI.Document")
miDoc.Create strTempImg
' Perform OCR.
miDoc.Images(0).ocr
' Retrieve and display word information.
Set miWord = miDoc.Images(0).Layout.Words(2)
strWordInfo = _
"Id: " & miWord.id & vbCrLf & _
"Line Id: " & miWord.LineId & vbCrLf & _
"Region Id: " & miWord.RegionId & vbCrLf & _
"Font Id: " & miWord.FontId & vbCrLf & _
"Recognition confidence: " & _
miWord.RecognitionConfidence & vbCrLf & _
"Text: " & miWord.Text
Set miWord = Nothing
Set miDoc = Nothing
OCRtest = strWordInfo
Return
Exit Function
err_hand:
Call CStatus(Error, 504, Err.Number, Err.description, strTempImg)
End Function
If you use MS Office 2010, you need install MODI firstly.
Then, you need to add reference to: Microsoft Office Document Imaging 1x.0 Type Library and you'll be able to use this code:
Sub OCRReader()
Dim doc1 As MODI.Document
Dim inputFile As String
Dim strRecText As String
Dim imageCounter As Integer
inputFile = Application.GetOpenFilename
strRecText = ""
Set doc1 = New MODI.Document
doc1.Create (inputFile)
doc1.OCR ' this will ocr all pages of a multi-page tiff file
For imageCounter = 0 To (doc1.Images.Count - 1) ' work your way through each page of results
strRecText = strRecText & doc1.Images(imageCounter).Layout.Text ' this puts the ocr results into a string
Next
fnum = FreeFile()
Open "C:\Test\testmodi.txt" For Output As fnum
Print #fnum, strRecText
Close #fnum
doc1.Close
End Sub
Above code comes from: https://www.mrexcel.com/forum/excel-questions/358499-read-data-tiff-file-using-modi-ocr-vba.html

vb.net pass folder path as commandline argument

I'm trying to pass a folder path via commandline argument to an application.
Problem: my folder path contains space " " in it's string. When I read the commandline arguments in the application I get my path chopped into pieces on the space " "
Sub Main()
Dim arguments As String() = System.Environment.GetCommandLineArgs()
For Each Arg As String In arguments
Console.WriteLine("Argument : " & Arg)
Next
Console.ReadLine()
End Sub
Edit: added code to build my argument
Private Sub btn_Copy_Click(sender As Object, e As EventArgs) Handles btn_Copy.Click
Dim args(3) As String
args(0) = """" & tb_CopyFromPath.Text & """"
args(1) = """" & tb_CopyToPath.Text & """"
args(2) = """" & tb_ItemTag.Text & """"
args(3) = """" & tb_Prefix.Text & """"
Dim argument As String
argument = args(0) & " " & args(1) & " " & args(2) & " " & args(3)
Process.Start("J:\VB.NET - EM AddIn\EM_Design_AddIn\CopyDesign\bin\Debug\CopyDesign.exe", argument)
End Sub
This result isn't okay. The first argument of the first path now contains a piece of the second path.
Edit: add value result from debug.
"""C:\VaultWorkspace\cadcampc\03-Vessel configurator - R2.0\Nozzles\WN_RF_ASME_B16.5\"" ""C:\VaultWorkspace\cadcampc\03-Vessel configurator - R2.0\Test Copy Design\N03"" ""N3"" ""12345-3"""
It is very simple. Just use ".
If you pass test test test parameters, you'll get 3 arguments. But if you write test "test test", you'll receive two parameters: test and test test.
Just pass it with double-quotes around it.
I.e:
app.exe "C:\Sub folder 1\Sub folder 2"
If you do it in code:
Process.Start("app.exe", """" & path & """")
The quotes specifies the start and end of an argument.
EDIT:
In your case you could do this instead:
argument = """" & args(0) & """ """ & args(1) & """ """ & args(2) & """ """ & args(3) & """"
Use CHR(34) to delimiter a string with spaces within.
See my answer here:
vb.net How to pass a string with spaces to the command line