VB looping and Excel - visual-studio-2010

I am writing in vb, and using excels parameters to convert .xls documents to pdf. The process works fine because I am using a string. What I need to know is to somehow loop through the source folder and then convert all files in that folder to pdf and put in the export folder keeping the original file name. Loops are seriously the bane of my existence in programming even though I know you need it for a solid foundation in this industry.
EXAMPLE:
Dim excelApplication As ApplicationClass = New ApplicationClass()
Dim excelWorkbook As Workbook = Nothing
Dim paramSourceBookPath As String = "C:\My_Projects\Testing\filename.xls"
Dim paramExportFilePath As String = "C:\My_Projects\Testing\filename.pdf"
Thanks in advance.

Try this:
Dim dir As New IO.DirectoryInfo(path)
Dim files As IO.FileInfo() = dir.GetFiles("*.xls")
For Each file In files
'Do Something
Next

Related

Converting a byte array with system locale set to Japanese in VB6

In my legacy VB6 application I'm receiving a zip file as a byte array from a webservice. This byte array is converted to a string using the StrConv function and stored on the file system.
Dim arr() As Byte
Dim sUnicode as String
nFile = FreeFile
arr = objHTTP.responseBody
sUnicode = StrConv(arr, vbUnicode)
Open sFile For Output As #nFile
Print #nFile, sUnicode
Close #nFile
So far so good, this has worked correctly for over a decade.
Now the application is used in Japan as well and the code above leads to a corrupt zip file.
I already found out that the issue is related to the Japanese system locale on the target system.
I tried passing the locale id 1033 to the StrConv function
StrConv(arr, vbUnicode, 1033)
Next I tried implementing the solution as descibed by this link
Encoding of Text Files in VB 6.0
Also I tried changing the system locale using the 'SetLocaleInfo' api-call.
None of the attempts have lead to a valid zip file on a OS with the system locale set to Japanese.
Does anybody know how to get a working solution?
Thanks in advance,
Jos
You should avoid the string conversion entirely. Try something like this:
Dim arr() As Byte
nFile = FreeFile
arr = objHTTP.responseBody
Open sFile For Binary As #nFile
Put #nFile, , arr
Close #nFile
This writes the contents of your array directly to the file.

VBS - Replace certain text entries in various files

I created a template for my test suite in QTP where the level of abstraction (parameterization) is sufficiently good.
I would now need to populate a new test suite from the existing pattern, thus replacing certain entries with other ones in various files.
For example one of the words I deliberately put in the script suite pattern is [Template], therefore I would need to copy and paste the template with a different name, change all the entries by [Template] to the new string and so forth.
Any code would be appreciated as my VBScript skills are not optimal ;)
Thanks in advance!
Use this demo script:
Option Explicit
Dim gMap : Set gMap = Createobject("Scripting.Dictionary")
Function replGMap(sM, nPos, sSrc)
replGMap = gMap(sM)
End Function
Dim reMap : Set reMap = New RegExp
reMap.Global = True
reMap.Pattern = "\[\w+\]"
gMap("[A]") = "abra"
gMap("[B]") = "cadabra"
WScript.Echo reMap.Replace("1[A]2[A]3[B]4[A]5", GetRef("replGMap"))
output:
abra2abra3cadabra4abra5
as a list of keywords to look up in the VBScript Docs. For using a function in .Replace, see here.
The FileSystemObject provides the means (Open/CreateTextFile, ReadAll, Write) to read and write files.

Save images in Outlook 2007

Programmatically, of course.
Having already asked this question on superuser, I'm looking at writing a simple macro to pull down the displayed image in an HTML message (email or feed) in outlook 2007, and allow me to save it to disk.
Unfortunately, I havent been able to find where in the OL object model I can reference either linked images, or the html content itself. Finding attached files is easy, its the linked/displayed images that is my issue.
Any help? Of course, if you have a better non-programmatic answer, I'll be glad to see that - over on superuser, of course...
This is based on the MSDN docs. I don't have Outlook to test it.
Assuming you have an email message open, you can call GetInspector method on the MailItem instance that you have & use its HTMLEditor property to get handle to the DOM.
From here on, you can call regular methods such as document.Images to get handle to all the image elements. I don't know, how one can save it locally to a disk but I am sure, there must be some method to do it.
I had a second look at shahkalpeshs answer and came up with the following solution:
(Written in Outlook 2003)
Option Explicit
Private Sub getImages()
Dim xmlhttp_ As xmlhttp
Dim htmldoc As Object
Dim currentImage As Object
Dim currentResponse() As Byte
Dim startTime As Date
Dim maxTime As Long
Dim pathFolder As String
Dim pathFull As String
Dim nrFile As Integer
pathFolder = "C:\YourFolder\Images\" '"(small fix for stackoverflow syntaxhighlighter)
maxTime = 30 ' max time to load 1 File in seconds '
If Me.ActiveWindow.CurrentItem.GetInspector.EditorType = olEditorHTML Then
Set htmldoc = Me.ActiveWindow.CurrentItem.GetInspector.HTMLEditor
Set xmlhttp_ = New xmlhttp
For Each currentImage In htmldoc.images
xmlhttp_.Open "GET", currentImage.src
If Left(currentImage.src, 8) <> "BLOCKED:" Then
xmlhttp_.Send
startTime = Now
pathFull = pathFolder & currentImage.nameProp
pathFull = Replace(pathFull, "?", vbNullString)
pathFull = Replace(pathFull, "&", vbNullString)
Do While xmlhttp_.readyState <> 4
If DateTime.DateDiff("s", startTime, Now) > maxTime Then Exit Do
DoEvents
Loop
If xmlhttp_.readyState = 4 Then
If Dir(pathFull) <> "" Then Kill pathFull
nrFile = freeFile
Open pathFull For Binary As #nrFile
currentResponse = xmlhttp_.responseBody
Put #nrFile, , currentResponse
Close #nrFile
End If
End If
Next currentImage
End If
Set xmlhttp_ = Nothing
Set currentImage = Nothing
Set htmldoc = Nothing
End Sub
This code will download all the images that are displayed in your ActiveWindow and save them in a folder.
You will need to add a Reference to Microsoft XML (any version >= 2.6 should work) through Tools->References in the VBA Editor
If you want to, you can also set a Reference to the Microsoft HTML Object Library and change:
Dim htmldoc As Object
Dim currentImage As Object
to:
Dim htmldoc As HTMLDocument
Dim currentImage As HTMLImg
Regarding your comment:
#marg, Thanks for the detailed response. I still cant believe the solution has to be so convoluted - the image is already displaying, why should I have to download it again? And what if I want to save only a single image? (In Outlook 2003, you were able to right click on the image and select save as... now no more.) Since this is the closes to an actual workable solution, and since there doesnt seem to be any better solution in current Outlook - i'm giving you the bounty...
I don't have 2007 to look for a non-programming solution.
I do not believe that the MailItem Object (CurrentItemin my solution is a MailItem) differs much between the versions (but I base that assumption on 0 % research :D) and I was not able to locate the direct local path where the displayed images are stored even though I am pretty sure they should be in your browsers cache-folder. Crawling your folder for a file with the name currentImage.nameProp and copying it to your destination folder would be an alternative solution. Simply redownloading the image should not be that bad :D

Visio to image command line conversion

At work we make pretty extensive use of Visio drawing as support for documentation. Unfortunately vsd files don't play nicely with our wiki or documentation extraction tools like javadoc, doxygen or naturaldocs. While it is possible to convert Visio files to images manually, it's just a hassle to keep the image current and the image files are bound to get out of date. And let's face it: Having generated files in revision control feels so wrong.
So I'm looking for a command line tool that can convert a vsd file to jpeg, png, gif or any image that can be converted to an image that a browser can display. Preferably it will run under unix, but windows only is also fine. I can handle the rest of the automation chain, cron job, image to image conversion and ssh, scp, multiple files, etc.
And that's why I'm turning to you: I can't find such a tool. I don't think I can even pay for such a tool. Is my Google-fu completely off? Can you help me?
I mean, it has got to be possible. There has to be a way to hook into Visio with COM and get it to save as image. I'm using Visio 2007 by the way.
Thanks in advance.
I slapped something together quickly using VB6, and you can download it at:
http://fournier.jonathan.googlepages.com/Vis2Img.exe
You just pass in the input visio file path, then the output file path (visio exports based on file extension) and optionally the page number to export.
Also here is the source code I used, if you want to mess with it or turn it into a VBScript or something, it should work, though you'd need to finish converting it to late-bound code.
hope that helps,
Jon
Dim TheCmd As String
Const visOpenRO = 2
Const visOpenMinimized = 16
Const visOpenHidden = 64
Const visOpenMacrosDisabled = 128
Const visOpenNoWorkspace = 256
Sub Main()
' interpret command line arguments - separated by spaces outside of double quotes
TheCmd = Command
Dim TheCmds() As String
If SplitCommandArg(TheCmds) Then
If UBound(TheCmds) > 1 Then
Dim PageNum As Long
If UBound(TheCmds) >= 3 Then
PageNum = Val(TheCmds(3))
Else
PageNum = 1
End If
' if the input or output file doesn't contain a file path, then assume the same
If InStr(1, TheCmds(1), "\") = 0 Then
TheCmds(1) = App.Path & "\" & TheCmds(1)
End If
If InStr(1, TheCmds(2), "\") = 0 Then
TheCmds(2) = App.Path & "\" & TheCmds(2)
End If
ConvertVisToImg TheCmds(1), TheCmds(2), PageNum
Else
' no good - need an in and out file
End If
End If
End Sub
Function ConvertVisToImg(ByVal InVisPath As String, ByVal OutImgPath As String, PageNum As Long) As Boolean
ConvertVisToImg = True
On Error GoTo PROC_ERR
' create a new visio instance
Dim VisApp As Visio.Application
Set VisApp = CreateObject("Visio.Application")
' open invispath
Dim ConvDoc As Visio.Document
Set ConvDoc = VisApp.Documents.OpenEx(InVisPath, visOpenRO + visOpenMinimized + visOpenHidden + visOpenMacrosDisabled + visOpenNoWorkspace)
' export to outimgpath
If Not ConvDoc.Pages(PageNum) Is Nothing Then
ConvDoc.Pages(PageNum).Export OutImgPath
Else
MsgBox "Invalid export page"
ConvertVisToImg = False
GoTo PROC_END
End If
' close it off
PROC_END:
On Error Resume Next
VisApp.Quit
Set VisApp = Nothing
Exit Function
PROC_ERR:
MsgBox Err.Description & vbCr & "Num:" & Err.Number
GoTo PROC_END
End Function
Function SplitCommandArg(ByRef Commands() As String) As Boolean
SplitCommandArg = True
'read through command and break it into an array delimited by space characters only when we're not inside double quotes
Dim InDblQts As Boolean
Dim CmdToSplit As String
CmdToSplit = TheCmd 'for debugging command line parser
'CmdToSplit = Command
Dim CharIdx As Integer
ReDim Commands(1 To 1)
For CharIdx = 1 To Len(CmdToSplit)
Dim CurrChar As String
CurrChar = Mid(CmdToSplit, CharIdx, 1)
If CurrChar = " " And Not InDblQts Then
'add another element to the commands array if InDblQts is false
If Commands(UBound(Commands)) <> "" Then ReDim Preserve Commands(LBound(Commands) To UBound(Commands) + 1)
ElseIf CurrChar = Chr(34) Then
'set InDblQts = true
If Not InDblQts Then InDblQts = True Else InDblQts = False
Else
Commands(UBound(Commands)) = Commands(UBound(Commands)) & CurrChar
End If
Next CharIdx
End Function
F# 2.0 script:
//Description:
// Generates images for all Visio diagrams in folder were run according to pages names
//Tools:
// Visio 2010 32bit is needed to open diagrams (I also installed VisioSDK32bit.exe on my Windows 7 64bit)
#r "C:/Program Files (x86)/Microsoft Visual Studio 10.0/Visual Studio Tools for Office/PIA/Office14/Microsoft.Office.Interop.Visio.dll"
open System
open System.IO
open Microsoft.Office.Interop.Visio
let visOpenRO = 2
let visOpenMinimized = 16
let visOpenHidden = 64
let visOpenMacrosDisabled = 128
let visOpenNoWorkspace = 256
let baseDir = Environment.CurrentDirectory;
let getAllDiagramFiles = Directory.GetFiles(baseDir,"*.vsd")
let drawImage fullPathToDiagramFile =
let diagrammingApplication = new ApplicationClass()
let flags = Convert.ToInt16(visOpenRO + visOpenMinimized + visOpenHidden + visOpenMacrosDisabled + visOpenNoWorkspace)
let document = diagrammingApplication.Documents.OpenEx(fullPathToDiagramFile,flags)
for page in document.Pages do
let imagePath = Path.Combine(baseDir, page.Name + ".png")
page.Export (imagePath)
document.Close()
diagrammingApplication.Quit()
let doItAll =
Array.iter drawImage getAllDiagramFiles
doItAll
You can try "Visio to image" converter
http://soft.postpdm.com/visio2image.html
Tested with MS Visio 2007 and 2010
There has to be a way to hook into Visio with COM and get it to save as image.
Why not try writing something yourself, then, if you know how to use COM stuff? After all, if you can't find anything already made to do it, and you know you can figure out how to do it yourself, why not write something to do it yourself?
EDIT: Elaborating a bit on what I stated in my comment: writing a script of some sort does seem to be your best option in this situation, and Python, at least, would be quite useful for that, using the comtypes library found here: http://starship.python.net/crew/theller/comtypes/ Of course, as I said, if you prefer to use a different scripting language, then you could try using that; the thing is, I've only really used COM with VBA and Python at this point (As an aside, Microsoft tends to refer to "Automation" these days rather than specifically referencing COM, I believe.) The nice thing about Python is that it's an interpreted language, and thus you just need a version of the interpreter for the different OSes you're using, with versions for Windows, OSX, Linux, Unix, etc. On the other hand, I doubt you can use COM on non-Windows systems without some sort of hack, so you may very well have to parse the data in the source files directly (and even though Visio's default formats appear to use some form of XML, it's probably one of those proprietary formats Microsoft seems to love).
If you haven't used Python before, the Python documentation has a good tutorial to get people started: http://docs.python.org/3.1/tutorial/index.html
And, of course, you'll want the Python interpreter itself: http://python.org/download/releases/3.1/ (Note that you may have to manually add the Python directory to the PATH environment variable after installation.)
When you write the script, you could probably have the syntax for running the script be something like "python visioexport.py <source/original file[ with path]>[ <new file[ with path]>]" (assuming the script file is in your Python directory), with the new file defaulting to a file of the same name and in the same folder/directory as the original (albeit with a different extension; in fact, if you wish, you could set it up to export to multiple formats, with the format defaulting to that of whatever default extension you choose and being specified by an alternate extension of you specify one in the file name. As well, you could likely set it up so that if you only have the new file name after the source file, no path specified, it'll save with that new file name to the source file's directory. And, of course, if you don't specify a path for the source file, just a file name, you could set it up to get the file from the current directory).
On the topic of file formats: it seems to me that converting to SVG might be the best thing to do, as it would be more space-efficient and would better reflect the original images' status as vectored images. On the other hand, the conversion from a Visio format to SVG is not perfect (or, at least, it wasn't in Visio 2003; I can't find a source of info similar to this one for Visio 2007), and as seen here, you may have to modify the resultant XML file (though that could be done using the script, after the file is exported, via parts of the Python standard library). If you don't mind the additional file size of bitmaps, and you'd rather not have to include additional code to fix resultant SVG files, then you probably should just go with a bitmap format such as PNG.

VBScript - image to binary

i'm not a VB programmer but i need a vbscript that convert image file (from local disk) to be converted to binary data and the passed to webservice. I realize how to pass data to webservice but i can't find how to convert the image file to binary data. I spend a lot of time to find some kind of solution but with no luck.
Can somebody help me?
Thanks!
Base64 encode VBS function (vb encoder algorithm), source code
http://www.motobit.com/tips/detpg_Base64Encode/
If you simply need to read the image file as binary data (in a way similar to reading text files), you can use the ADODB.Stream object:
Const adTypeBinary = 1
Dim oStream, bData
Set oStream = CreateObject("ADODB.Stream")
oStream.Type = adTypeBinary
oStream.Open
oStream.LoadFromFile "C:\MyImage.png"
bData = oStream.Read
' Do whatever you need with bData
...

Resources