Read and store data using vb script - file-io

I have a file with following content
aaaaaaaaa filename1.txt
bbbbbbbbbb filename2.dat
i want to read this file and store data to the relevent file seperately.
eg :- aaaaa ---> filename1.txt
Could someone please tell me the way to do this? If you have any worked through examples, that would be a real help!
Sub Main
Set ctlpath = "\\Download_Directory\CA.ctl"
Set subDirectory = "AUB"
Set MkrExtention = ".mkr"
ReadCtl(ctlpath,subDirectory,MkrExtention )
End Sub
Function ReadCtl(ctlFileName,ctlSubDirectory,MarkerFileExtension)
Const ForReading = 1
Const ForWriting = 2
Dim lineData,hashValue,fileName,fileToWrite
Set objFSO = CreateObject("Scripting.FileSystemObject")
If objFSO.FileExists(ctlFileName) Then
Set objFile = objFSO.OpenTextFile(ctlFileName, ForReading)
Do Until objFile.AtEndOfStream
lineData = objFile.ReadLine
hashValue =Split(lineData," ") (0)
fileName =Split(lineData," ") (1)
WriteFileText("\\Download"+ctlSubDirectory+"
\"+fileName+MarkerFileExtension,hashValue)
Loop
objFile.Close
objFSO.Close
End If
ReadCtl = True
End Function
Function WriteFileText(sFilePath, sText)
Dim objFSO1 'As FileSystemObject
Dim objTextFile 'As Object
Set objFSO1 = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFSO1.CreateTextFile(sFilePath, True)
' Write hash data in to the file .mkr file
objTextFile.Write (sText)
objTextFile.Close
objFSO1.Close
End Function

A long time since you asked this, surprises me nobody answered, is simple enough.
Hope you'r still around, anyway here for reference. This is no real hash like eg in Ruby of course but i kept enough of your script so that you can compare.
ReadCtl("file2hash1.txt")
function ReadCtl(ctlFileName)
const ForReading = 1, ForWriting = 2, ForAppending = 8, createIfNeeded = true
set oFso = createObject("Scripting.FileSystemObject")
Set oRegExpre = new RegExp
oRegExpre.Global = true
oRegExpre.Pattern = "(.*) +(.*)"
if oFso.FileExists(ctlFileName) then
set objFileRead = oFso.OpenTextFile(ctlFileName, ForReading)
do until objFileRead.AtEndOfStream
lineData = objFileRead.ReadLine
hashValue = oRegExpre.Replace(lineData,"$1")
fileName = oRegExpre.Replace(lineData,"$2")
if oFso.fileExists(fileName) then
modus = ForAppending
else
modus = ForWriting
end if
set objFileWrite = oFso.OpenTextFile(fileName, modus, createIfNeeded)
objFileWrite.writeLine hashValue
objFileWrite.close
loop
objFileRead.close
end if
set oFso = nothing
end function

Related

LibreOffice Writer API - Cursors and text selection / replacement from VB6

I have been attempting to replace Office OLE in a vb6 application with LibreOffice.
I have had some success, however, I am falling short trying to search for text, then create a cursor based on the text that was found, then insert an image at that cursors point in the document.
I have been able to piece together working code that will allow me to search for text, replace text and insert an image, however, I cannot seem to figure out how to create a cursor that will allow me to insert an image at the pace where the text is that I have found . In the provided example, the [PICTUREPLACEHOLDER] text in the document.
Has anyone ever done this before and do they have any suggestions how I can create a cursor that will allow me to specify where the image will be inserted.
I have included the code for the VB6 test app so you can see the source code to see how its currently working.
Any suggestions would be very much appreciated.
Please Note - this is experimental code - very rough and ready - not final code by a long shot - just trying to figure out how this works with LibreOffice Writer.
To run this, you will need to create an empty vb6 app with a button.
You also need LibreOffice installed.
Many thanks
Rod.
Sub firstOOoProc()
Dim oSM 'Root object for accessing OpenOffice from VB
Dim oDesk, oDoc As Object 'First objects from the API
Dim arg() 'Ignore it for the moment !
'Instanciate OOo : this line is mandatory with VB for OOo API
Set oSM = CreateObject("com.sun.star.ServiceManager")
'Create the first and most important service
Set oDesk = oSM.createInstance("com.sun.star.frame.Desktop")
Dim oProvider As Object
Set oProvider = oSM.createInstance("com.sun.star.graphic.GraphicProvider")
'Open an existing doc (pay attention to the syntax for first argument)
Set oDoc = oDesk.loadComponentFromURL("file:///c:/dev/ooo/testfile.doc", "_blank", 0, arg())
' now - replace some text in the document
Dim Txt
Txt = oDoc.GetText
Dim TextCursor
TextCursor = Txt.CreateTextCursor
' attempt to replace some text
Dim SearchDescriptor
Dim Replace
Replace = oDoc.createReplaceDescriptor
Replace.SearchString = "[TESTDATA1]"
Replace.ReplaceString = "THIS IS A TEST"
oDoc.replaceAll Replace
Dim searchCrtiteria
SearchDescriptor = oDoc.createReplaceDescriptor
' Now - attempt try to replace some text with an image
SearchDescriptor.setSearchString ("[PICTUREPLACEHOLDER]")
SearchDescriptor.SearchRegularExpression = False
Dim Found
Found = oDoc.findFirst(SearchDescriptor)
' create cursor to know where to insert the image
Dim oCurs As Object
Set thing = oDoc.GetCurrentController
Set oCurs = thing.GetViewCursor
' make hte call to insert an image from a file into the document
InsertImage oDoc, oCurs, "file:///c:/dev/ooo/imagefilename.jpg", oProvider
'Save the doc
Call oDoc.storeToURL("file:///c:/dev/ooo/test2.sxw", arg())
'Close the doc
oDoc.Close (True)
Set oDoc = Nothing
oDesk.Terminate
Set oDesk = Nothing
Set oSM = Nothing
End Sub
Function createStruct(strTypeName)
Set classSize = objCoreReflection.forName(strTypeName)
Dim aStruct
classSize.CreateObject aStruct
Set createStruct = aStruct
End Function
Sub InsertImage(ByRef oDoc As Object, ByRef oCurs As Object, sURL As String, ByRef oProvider As Object)
' Init variables and instance object
Dim oShape As Object
Dim oGraph As Object
Set oShape = oDoc.createInstance("com.sun.star.drawing.GraphicObjectShape")
Set oGraph = oDoc.createInstance("com.sun.star.text.GraphicObject")
'Set oProvider = serviceManager.CreateInstance("com.sun.star.graphic.GraphicProvider")
' Add shape to document
oDoc.getDrawPage.Add oShape
' Set property path of picture
Dim oProps(0) As Object
Set oProps(0) = MakePropertyValue("URL", sURL)
' Get size from picture to load
Dim oSize100thMM
Dim lHeight As Long
Dim lWidth As Long
Set oSize100thMM = RecommendGraphSize(oProvider.queryGraphicDescriptor(oProps))
If Not oSize100thMM Is Nothing Then
lHeight = oSize100thMM.Height
lWidth = oSize100thMM.Width
End If
' Set size and path property to shape
oShape.graphic = oProvider.queryGraphic(oProps)
' Copy shape in graphic object and set anchor type
oGraph.graphic = oShape.graphic
oGraph.AnchorType = 1 'com.sun.star.Text.TextContentAnchorType.AS_CHARACTER
' Remove shape and resize graphix
Dim oText As Object
Set oText = oCurs.GetText
oText.insertTextContent oCurs, oGraph, False
oDoc.getDrawPage.Remove oShape
If lHeight > 0 And lWidth > 0 Then
Dim oSize
oSize = oGraph.Size
oSize.Height = lHeight * 500
oSize.Width = lWidth * 500
oGraph.Size = oSize
End If
End Sub
'
'Converts a Ms Windows local pathname in URL (RFC 1738)
'Todo : UNC pathnames, more character conversions
'
Public Function ConvertToUrl(strFile) As String
strFile = Replace(strFile, "\", "/")
strFile = Replace(strFile, ":", "|")
strFile = Replace(strFile, " ", "%20")
strFile = "file:///" + strFile
ConvertToUrl = strFile
End Function
'
'Creates a sequence of com.sun.star.beans.PropertyValue s
'
Public Function MakePropertyValue(cName, uValue) As Object
Dim oStruct, oServiceManager As Object
Set oServiceManager = CreateObject("com.sun.star.ServiceManager")
Set oStruct = oServiceManager.Bridge_GetStruct("com.sun.star.beans.PropertyValue")
oStruct.Name = cName
oStruct.Value = uValue
Set MakePropertyValue = oStruct
End Function
'
'A simple shortcut to create a service
'
Public Function CreateUnoService(strServiceName) As Object
Dim oServiceManager As Object
Set oServiceManager = CreateObject("com.sun.star.ServiceManager")
Set CreateUnoService = oServiceManager.createInstance(strServiceName)
End Function
Public Function RecommendGraphSize(oGraph)
Dim oSize
Dim lMaxW As Double
Dim lMaxH As Double
lMaxW = 6.75 * 2540
lMaxH = 9.5 & 2540
If IsNull(oGraph) Or IsEmpty(oGraph) Then
Exit Function
End If
oSize = oGraph.Size100thMM
If oSize.Height = 0 Or oSize.Width = 0 Then
oSize.Height = oGraph.SizePixel.Height * 2540# * Screen.TwipsPerPixelY() '/ 1440
oSize.Width = oGraph.SizePixel.Width * 2540# * Screen.TwipsPerPixelX() '/ 1440
End If
If oSize.Height = 0 Or oSize.Width = 0 Then
Exit Function
End If
If oSize.Width > lMaxW Then
oSize.Height = oSizeHeight * lMax / oSize.Width
oSize.Width = lMaxW
End If
If oSize.Height > lMaxH Then
oSize.Width = oSize.Width * lMaxH / oSize.Height
oSize.Height = lMaxH
End If
RecommendGraphSize = oSize
End Function
Private Sub Command1_Click()
firstOOoProc
End Sub
The content of the testFile.Doc file is as shown below:
This is a test File
[TESTDATA1]
[PICTUREPLACEHOLDER]
It looks like you need to move the view cursor to the found location.
Found = oDoc.findFirst(SearchDescriptor)
oVC = oDoc.getCurrentController().getViewCursor()
oVC.gotoRange(Found, False)
oVC.setString("")

A function to get the length(time) of an audio file

I have got this far but when I set the value for 'Folder' it is empty and the 'FolderPath' is "F:\Video Clips" what am I doing wrong
Function GetFileLength(FolderPath As String, FileName As String) As Date
'
' Get the run time of a audio/video file
'
' Set Up
Dim Shell As Object
Dim Folder As Object
Dim File As Object
Set Shell = CreateObject("Shell.Application")
Set Folder = Shell.Namespace(FolderPath)
'Set Folder = Shell.Namespace("F:\Video Clips")
Set File = Folder.ParseName(FileName)
' Get time
If LCase(Right(FileName, 3)) = "avi" Then
GetFileLength = Folder.GetDetailsOf(File, 27)
Else
GetFileLength = ""
End If
End Function
Try it with the data type variant for the folder path in your function. Also have a look at the documentation of Namespace.
Function GetFileLength(FolderPath As Variant, FileName As String) As Date
'
' Get the run time of a audio/video file
'
' Set Up
Dim Shell As Object
Dim Folder As Object
Dim File As Object
Set Shell = CreateObject("Shell.Application")
Set Folder = Shell.Namespace(FolderPath)
'Set Folder = Shell.Namespace("F:\Video Clips")
Set File = Folder.ParseName(FileName)
' Get time
If LCase(Right(FileName, 3)) = "avi" Then
GetFileLength = Folder.GetDetailsOf(File, 27)
Else
GetFileLength = ""
End If
End Function
PS Another bug you have is that the else condition GetFileLength = "" will fail because a string is not a date. Maybe you should use GetFileLength = CDate(0) or whatever you think is appropriate.

Powerpoint macro to get the last modified date of a file

I want to get the last modified date of a ppt file and put the condition : if it's in after thursady of the week than out else go on. That's what i wrote but it doesn't work!
Sub proprietes()
Set fs = CreateObject("Scripting.FileSystemObject")
FilePath = "C:\Users\Moez\Desktop\Macro Project\test v2"
Set f = fs.GetFile(FilePath)
fileModDate = f.DateLastModified
End Sub
i always get the mistake in Set f = fs.GetFile(FilePath)!!
Could you help me please?
thanks a lot
Try this
Sub proprietes()
Set fs = CreateObject("Scripting.FileSystemObject")
FilePath = "C:\Users\....\Desktop\TestPPT.pptx"
Set f = fs.GetFile(FilePath)
fileModDate = f.DateLastModified
End Sub
maybe something like this
FilePath = Dir("C:\Users\Moez\Desktop\Macro Project\test v2*")
fileModDate = FileDateTime(FilePath)
https://www.techonthenet.com/excel/formulas/filedatetime.php

VBSCRIPT to read multi files into an array then write them to a single file

As the title suggests, I have three separate text files that I want to join together in a certain order (i.e., append file1, file2, file3 (in order) to make file4).
From what I've read, to do this with VBScript would require the FileSystemObject to read the files into an array then write the contents to the new file (I am open to whatever works with VBScript if suggested)
I'm having the following issues with my code:
1) The script runs, but produces no data
2) After I get it to run, it is imperative that the files append to the output file in the order of the array in the order (per line) I suggest above.
Here is the Array example I'm working with :
CODE
Const ForReading = 1
Dim arrServiceList(2)
arrServiceList(0) = strText1
arrServiceList(1) = strText2
arrServiceList(2) = strText3
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objOutputFile = objFSO.CreateTextFile("output.txt")
Set objTextFile1 = objFSO.OpenTextFile("C:\Users\95540\Desktop\Sample1.txt", ForReading)
Set objTextFile2 = objFSO.OpenTextFile("C:\Users\95540\Desktop\Sample2.txt", ForReading)
Set objTextFile3 = objFSO.OpenTextFile("C:\Users\95540\Desktop\Sample3.txt", ForReading)
strText1 = objTextFile1.ReadAll
objTextFile1.Close
strText2 = objTextFile2.ReadAll
objTextFile2.Close
strText3 = objTextFile3.ReadAll
objTextFile3.Close
objOutputFile.WriteLine arrServiceList(0)
objOutputFile.Close
====================
UPDATE TO MY CODE 5-15-15 (Description of corrections in below post)
CODE
Const ForReading = 1
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objOutputFile = objFSO.CreateTextFile("output.txt")
Set objTextFile1 = objFSO.OpenTextFile("C:\Users\Brill\Desktop\Grab1.txt", ForReading)
Set objTextFile2 = objFSO.OpenTextFile("C:\Users\Brill\Desktop\Grab2.txt", ForReading)
Set objTextFile3 = objFSO.OpenTextFile("C:\Users\Brill\Desktop\Grab3.txt", ForReading)
Do While objTextFile1.AtEndOfStream <> True
Do While objTextFile2.AtEndOfStream <> True
Do While objTextFile3.AtEndOfStream <> True
strText1 = objTextFile1.ReadLine
objOutputFile.Write strText1 & vbTab
strText2 = objTextFile2.ReadLine
objOutputFile.Write strText2 & vbTab
strText3 = objTextFile3.ReadLine
objOutputFile.Write strText3 & vbTab & vbCrLf
Loop
Loop
Loop
objOutputFile.Close
objTextFile1.Close
objTextFile2.Close
objTextFile3.Close
The below works.
Problems with your script. 1. You were assigning the variables to the array before you had populated them. 2. You were not writing all the elements of the array.
Const ForReading = 1
Dim arrServiceList(2)
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objOutputFile = objFSO.CreateTextFile("output.txt")
Set objTextFile1 = objFSO.OpenTextFile("C:\Users\95540\Desktop\Sample1.txt", ForReading)
Set objTextFile2 = objFSO.OpenTextFile("C:\Users\95540\Desktop\Sample2.txt", ForReading)
Set objTextFile3 = objFSO.OpenTextFile("C:\Users\95540\Desktop\Sample3.txt", ForReading)
strText1 = objTextFile1.ReadAll
objTextFile1.Close
strText2 = objTextFile2.ReadAll
objTextFile2.Close
strText3 = objTextFile3.ReadAll
objTextFile3.Close
arrServiceList(0) = strText1
arrServiceList(1) = strText2
arrServiceList(2) = strText3
objOutputFile.WriteLine arrServiceList(0)
objOutputFile.WriteLine arrServiceList(1)
objOutputFile.WriteLine arrServiceList(2)
objOutputFile.Close
Merging/Zipping more then one collection (e.g. some 'column files') into one collection (e.g. a 'table file') is a standard problem with a standard solution strategy (which doesn't involve reading "the files into an array" at all).
This demo code:
Option Explicit
Dim goFS : Set goFS = CreateObject("FileSystemObject")
Dim oFZip : Set oFZip = New cFZip
oFZip.m_aIFSpecs = Split("..\data\a.txt ..\data\b.txt ..\data\c.txt")
oFZip.zip "..\data\abc.txt"
WScript.Echo goFS.OpenTextFile("..\data\abc.txt").ReadAll()
Class cFZip
Public m_aIFSpecs ' array of input files
Function zip(sOFSpec)
Dim tsOut : Set tsOut = goFS.CreateTextFile(sOFSpec)
Dim nUBFiles : nUBFiles = UBound(m_aIFSpecs)
ReDim aFiles(nUBFiles)
Dim f
For f = 0 To nUBFiles
Set aFiles(f) = goFS.OpenTextFile(m_aIFSpecs(f))
Next
Dim bDone
Do
Redim aData(UBound(m_aIFSpecs))
bDone = True
For f = 0 To nUBFiles
If Not aFiles(f).AtEndOfStream Then
bDone = False
aData(f) = aFiles(f).ReadLine()
End If
Next
If Not bDone Then tsOut.WriteLine Join(aData, ",")
Loop Until bDone
For f = 0 To nUBFiles
aFiles(f).Close
Next
tsOut.Close
End Function
End Class
output:
1,10,100
2,20,200
3,30,300
4,,400
,,500
shows the basic approach. I use a Class to make experiments/specific adaptions (e.g. delimiter, quoting, ...) easier.

PDF page count not correct

I was just wondering why the vbs code in the link below is not counting pdf pages correctly? It seems to under count by half or more the number of pages that actually exist in each pdf.
http://docs.ongetc.com/index.php?q=content/pdf-pages-counting-using-vb-script
Here is the code if you can not access the link above:
' By Chanh Ong
'File: pdfpagecount.vbs
' Purpose: count pages in pdf file in folder
Const OPEN_FILE_FOR_READING = 1
Set gFso = WScript.CreateObject("Scripting.FileSystemObject")
Set gShell = WScript.CreateObject ("WSCript.shell")
Set gNetwork = Wscript.CreateObject("WScript.Network")
directory="."
set base=gFso.getFolder(directory)
call listPDFFile(base)
Function ReadAllTextFile(filespec)
Const ForReading = 1, ForWriting = 2
Dim f
Set f = gFso.OpenTextFile(filespec, ForReading)
ReadAllTextFile = f.ReadAll
End Function
function countPage(sString)
Dim regEx, Match, Matches, counter, sPattern
sPattern = "/Type\s*/Page[^s]" ' capture PDF page count
counter = 0
Set regEx = New RegExp ' Create a regular expression.
regEx.Pattern = sPattern ' Set pattern "^rem".
regEx.IgnoreCase = True ' Set case insensitivity.
regEx.Global = True ' Set global applicability.
set Matches = regEx.Execute(sString) ' Execute search.
For Each Match in Matches ' Iterate Matches collection.
counter = counter + 1
Next
if counter = 0 then
counter = 1
end if
countPage = counter
End Function
sub listPDFFile(grp)
Set pf = gFso.CreateTextFile("pagecount.txt", True)
for each file in grp.files
if (".pdf" = lcase(right(file,4))) then
larray = ReadAllTextFile(file)
pages = countPage(larray)
wscript.echo "The " & file.name & " PDF file has " & pages & " pages"
pf.WriteLine(file.name&","&pages)
end if
next
pf.Close
end sub
Thanks
The solution offered (and accepted) will only work for a limited number of PDF documents. Since PDF documents frequently compress large chunks of data including page metadata, crude regular expression searches for "type\s*/page[^s]" will often miss pages.
The only really reliable solution is to very laboriously decompose the PDF document. I'm afraid I don't have a working VBS solution but I have written a Delphi function which demonstrates how to do this (see http://www.angusj.com/delphitips/pdfpagecount.php).
Try this
Function getPdfPgCnt(ByVal sPath)
Dim strTStr
With CreateObject("Adodb.Stream")
.Open
.Charset = "x-ansi"
.LoadFromFile sPath
strTStr = .ReadText(-1)
End With
With (New RegExp)
.Pattern = "Type\s+/Page[^s]"
.IgnoreCase = True
.Global = True
getPdfPgCnt = .Execute(strTStr).Count
End With
If getPdfPgCnt = 0 Then getPdfPgCnt = 1
End Function
'Usage : getPdfPgCnt("C:\1.pdf")
Update #1~#2:
Option Explicit
Private Function getPdfPgCnt(ByVal sPath) 'Returns page count of file on passed path
Dim strTStr
With CreateObject("Adodb.Stream")
.Open
.Charset = "x-ansi"
.LoadFromFile sPath
strTStr = .ReadText(-1)
End With
With (New RegExp)
.Pattern = "Type\s*/Page[^s]"
.IgnoreCase = True
.Global = True
getPdfPgCnt = .Execute(strTStr).Count
End With
If getPdfPgCnt = 0 Then getPdfPgCnt = 1
End Function
'--------------------------------
Dim oFso, iFile
Set oFso = CreateObject("Scripting.FileSystemObject")
'enumerating pdf files in vbs's base directory
For Each iFile In oFso.getFolder(oFso.GetParentFolderName(WScript.ScriptFullName)).Files
If LCase(oFso.GetExtensionName(iFile)) = "pdf" Then WScript.Echo iFile & " has "& getPdfPgCnt(iFile)&" pages."
Next
Set oFso = Nothing
'--------------------------------