vba saving images from word without using binary - vba

Ive tried using several methods to save images, one was using binary code. the issue with that is that it saves a few hidden characters in the file name, and then the file becomes funky, where the only program that can open it is mspaint, and when i try to resave the file, it defaults to wanting to save the image as *heic format.
anyone have any ideas on how to save an inlineshape in Word to your desktop.
```
Open strOutFileName For Binary Access Write As #1
i = i + 1
vData = shapeCurrent.Range.EnhMetaFileBits
lWritePos = 1
'put writes to the file that has been created
Put #1, lWritePos, vData
Close #1
```

Related

Best way to export an Icon Image from Access?

I have about 50 icon images (.ico) on an Access form, however I don't have them stored on a disk. I'd like to export them from Access onto a disk location.
I tried the suggested solution on this thread:
Access - Export images from Image controls in forms
I couldn't open the resulting file, probably because my images are (.ico) rather than (.png)
EDIT: I'm able to copy the icons into paint, save them as pngs, then use an online converter to convert them to icons. Pretty time consuming but it works.
You can use this code blow.
It will save the content of all image controls of the provided form to files in the same folder.
Beware that some image controls contain 'strange' binary formats which maybe can't be displayed properly by every tool.
Also you would have to take care to assign a correct file extension after exporting yourself.
Place the code in a new module, then open the form in design view and call it like this: SaveAllImageControls Forms("MyForm")
Public Sub SaveAllImageControls(ByRef sourceForm As Form)
Dim item As control
For Each item In sourceForm.Controls: Do
If item.ControlType <> acImage Then Exit Do
If IsNull(item.PictureData) Then Exit Do
Dim bArray() As Byte
bArray = item.PictureData
Dim filename As String
filename = Application.CurrentDb.Name & "-" & sourceForm.Name & "-" & item.Name & ".binary"
Dim fileNumber As Integer
fileNumber = FreeFile
Open filename For Binary As fileNumber
Put fileNumber, , bArray
Close fileNumber
Loop While False: Next item
End Sub
The simplest solution is probably to export all the ico files and then process them with ImageMagick. You can run something like
convert image.ico image.png
either as part of the code you linked to or as a plain one time call in a command prompt.

VBA - Reading PDF as String - Cannot sometimes but can other times - 'Run time error 62' [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
You can open PDFs in text editors to see the structure of how the PDF is written.
Using VBA I have opened a PDF as a text file and go to extract the text and save it as a string variable in VBA. I want to look through this text to find a specific element; a polyline (called sTreamTrain) and get the vertices of the polyline by using the InStr function.
When i add more vertices to the polyline I cannot seem to extract the text string of the pdf. I get the error 'Run time error 62' which I do not understand what it means or what about the PDF has changed to now have this error.
Attached (via the link) is a PDF that I can read (Document 15) and a PDF I cannot read (Document 16). I have checked in excel so see that the vertices are present in both files. Also there is a copy of my VBA script as a notepad document and also my excel file (but it is difficult to find in my excel file - the script is "Module 6" function called "CoordExtractor_TestBuild01()")
Link:
https://drive.google.com/open?id=1zOhwnFWZZfy9bTAxKiQFSl7qiQLlYIJV
Code snippet of the text extraction process below to reproduce the problem (given an applicable pdf is used):
Sub CoordExtractor_TestBuild01()
'Opening the PDF and getting the coordinates
Dim TextFile As Integer
Dim FilePath As String
Dim FileContent As String
'File Path of Text File
FilePath = "C:\Users\KAllan\Documents\WorkingInformation\sTreamTrain\Document16 - Original.pdf"
'Determine the next file number available for use by the FileOpen function
TextFile = FreeFile
'Open the text file in a Read State
Open FilePath For Input As TextFile
'Store file content inside a variable
Dim Temp As Long
Temp = LOF(TextFile)
FileContent = Input(LOF(TextFile), TextFile)
'Clost Text File
Close TextFile
End Sub
I would like someone to let me know what runtime error 62 is in this context and propose any workflows to get around it in future. Also, I would like to know whether there certain characters you cannot store as strings? - Perhaps these are included when I increase the number of vertices past a certain number.
Also I would prefer to keep the scrips quite simple and not use external libraries because I want to share the script when it is done so others can use it thus its simpler if it works without extra dependencies etc, however, any and all advice welcome since this is only the first half of this project.
Thank you very much.
According to the MSDN documentation, this error is caused by the file containing
...blank spaces or extra returns at the end of the file or the syntax
is not correct.
Since your code works sometimes on documents with very similar names and content to documents where it doesn't work, we can rule out syntax errors in this case.
You can clean up the file contents before processing it any further by replacing the code at the top of your macro with the one below. With this I can read and extract information from your Document16.pdf:
Sub CoordExtractor_TestBuild01()
'Purpose to link together the extracting real PDF information and outputting the results onto a spreadsheet
'########################################################################################
'Opening the PDF and getting the coordinates
Dim n As Long
Dim TextFile As Integer
Dim FilePath As String
Dim FileContent As String
'File Path of Text File
FilePath = "C:\TEST\Document16.pdf" ' change path
'Determine the next file number available for use by the FileOpen function
TextFile = FreeFile
'Open the text file in a Read State
Open FilePath For Input As TextFile
Dim strTextLine As String
Dim vItem As Variant
Line Input #1, strTextLine
vItem = Split(strTextLine, Chr(10))
' clean file of garbage information line by line
For n = LBound(vItem) To UBound(vItem)
' insert appropriate conditions here - in this case if the string "<<" is present
If InStr(1, vItem(n), "<<") > 0 Then
If FileContent = vbNullString Then
FileContent = vItem(n)
Else
FileContent = FileContent & Chr(10) & vItem(n)
End If
End If
Next n
'Clost Text File
Close TextFile
' insert the rest of the code here

VBA Reading From a UCS-2 Little Endian Encoded Text File

I have a whole bunch of text files that are exported from Photoshop that I need to import into an Excel document. I wrote a macro to get the job done and it seemed to work just fine for my test document but when I tried loading in some of the actual files produced by Photoshop Excel started putting all the data in a separate column except for the first line.
My code that reads the text file:
Open currentDocPath For Input As stream
Do Until EOF(stream)
Input #stream, currentLine
columnContents = Split(currentLine, vbTab)
For n = 0 To UBound(columnContents)
ActiveSheet.Cells(row, Chr(64 + colum + n)).Value = columnContents(n)
Next n
row = row + 1
Loop
Close stream
The text files I am reading look like this, only with much more data:
"Name" "Data" "Info" "blah"
"Name1" "Data1" "Info1" "blah1"
"Name2" "Data2" "Info2" "blah2"
The problem seemed pretty trivial, but when I load it into excel, instaed of looking like it does above it looks like this:
ÿþ"Name" "Data" "Info" "blah"
Name1
Data1
Info1
blah1
Name2
Data2
Info2
blah2
Now I am not sure why this is happening. It seems like the first two characters in the first row are there because those bytes declare the text encoding. Somehow those characters keep the first row formatted correctly while the remaining rows lose their quotation marks and all get moved to new lines.
Could someone who understands UCS-2 Little Endian text encoding explain how I can work around this? When I convert the files to ASCII it works fine.
Cheers!
edit: Okay so I understand now that the encoding is UTF-16 (I don't know a whole lot about character encoding). My main issue is that it's formatting strangely and I don't understand why or how to fix it. Thanks!
As I mentioned in my comment, it appears the file you're trying to import is encoded in UTF-16.
In this vbaexpress.com article, someone suggested that the following should work:
Dim GetOpenFile As String
Dim MyData As String
Dim r As Long
GetOpenFile = Application.GetOpenFilename
r = 1
Open GetOpenFile For Input As #1
Do While Not EOF(1)
Line Input #1, MyData
Cells(r, 1).Value = MyData
r = r + 1
Loop
Close #1
Obviously I can't test it myself, but maybe it'll help you.
Why not just tell excel to import the file. MS has probably put hundreds of thousands of person hours into that code. Record the importation to get easy code.
Remember Excel is a tool for non programmers to do programming things. Use it instead of trying to replace it.
These are the replacement file functions that you use for new code. Add a reference to Microsoft Scripting Runtime.
Opens a specified file and returns a TextStream object that can be used to read from, write to, or append to the file.
object.OpenTextFile(filename[, iomode[, create[, format]]])
Arguments
object
Required. Object is always the name of a FileSystemObject.
filename
Required. String expression that identifies the file to open.
iomode
Optional. Can be one of three constants: ForReading, ForWriting, or ForAppending.
create
Optional. Boolean value that indicates whether a new file can be created if the specified filename doesn't exist. The value is True if a new file is created, False if it isn't created. If omitted, a new file isn't created.
format
Optional. One of three Tristate values used to indicate the format of the opened file. If omitted, the file is opened as ASCII.
The format argument can have any of the following settings:
Constant Value Description
TristateUseDefault
-2
Opens the file using the system default.
TristateTrue
-1
Opens the file as Unicode.
TristateFalse
0
Opens the file as ASCII.

Extract data from PDF file with VB.Net

I'm trying to pull some data from a large PDF file in VB.Net I found the following code online, but it's not helping:
Sub PrintPDF (strPDFFileName as string)
Dim sAdobeReader as String
'This is the full path to the Adobe Reader or Acrobat application on your computer
sAdobeReader = "C:\Program Files\Adobe\Acrobat 6.0\Reader\AcroRd32.exe"
RetVal = Shell(sAdobeReader & "/P" & Chr(34) & sStrPDFFileName & Chr(34), 0)
End Sub
I'm really lost. Any ideas?
/P will just display load the file and display the Print dialog - dead end.
You will probably need a library of some sort to get to the contents of the PDF.
If the file has a very simple structure you maybe able to extract the data just by reading the bytes. See if you can open it with a file like Notepad++ and see the contents.
BTW VS2010 has several editors for looking at/editing files:
File, Open File... pick the file then use the dropdown on the Open button.

copy image to clipboard and let it be pasted as file (vb.net)

I have a picture box, and if I use snipet below:
Clipboard.SetImage(PictureBox.image)
Then I can only paste the image into things like Paint and MS word. I can't paste it as a file into a folder/desktop.
So how can I copy the image to the clipboard and if gets pasted to a folder then it becomes a file?
If you're using .net and your ultimate goal is to save the file, there's a LOT easier way,
Here the code in C#, porting it into VB.net won't be hard, I'm just too lazy to do that :)
Anyway, you do have to save it somewhere before you can paste it so...
It loads the file to the Picture box and again saves it to a file, (lame, I know)
and set the clipboard data as a copy operation
then when you paste (Ctrl+V) it, it gets pasted.
C#
__
Bitmap bmp;
string fileName=#"C:\image.bmp";
//here I assume you load it from a file, you might get the image from somewhere else, your code may differ
pictureBox1.Image=(Image) Bitmap.FromFile(fileName);
bmp=(Bitmap)pictureBox1.Image;
bmp.Save(#"c:\image2.bmp");
System.Collections.Specialized.StringCollection st = new
System.Collections.Specialized.StringCollection();
st.Add(#"c:\image2.bmp");
System.Windows.Forms.Clipboard.SetFileDropList(st);
</pre>
and viola tries pasting in a folder the file image2.bmp will be pasted.
Here's basically what #Vivek posted but ported to VB. Up-vote his if this works for you. What you have to understand is that explorer will only allow you to paste files, not objects (AFAIK anyway). The reason is because if you copy image data to the clipboard, what format should it paste in? PNG, BMP, JPG? What compression settings? So like #Vivek said, you need to think those over, create a file on your own somewhere on the system and use SetFileDropList which will add the temp file to the clipboard.
' Add it as an image
Clipboard.SetImage(PictureBox1.Image)
'Create a JPG on disk and add the location to the clipboard
Dim TempName As String = "TempName.jpg"
Dim TempPath As String = System.IO.Path.Combine(My.Computer.FileSystem.SpecialDirectories.Temp, TempName)
Using FS As New System.IO.FileStream(TempPath, IO.FileMode.Create, IO.FileAccess.Write, IO.FileShare.Read)
PictureBox1.Image.Save(FS, System.Drawing.Imaging.ImageFormat.Jpeg)
End Using
Dim Paths As New System.Collections.Specialized.StringCollection()
Paths.Add(TempPath)
Clipboard.SetFileDropList(Paths)