Excel 2010 to PDF using VB - visual-studio-2010

I have hundreds of Excel files being saved in a folder. I was wondering how I could write something in Visual Basic to convert these to PDF. Is there a way to call to Excel 2010's Save As function to save them in a different folder? I have checked Google and on here and all I can find is references to third party applications.

Dim excel As Microsoft.Office.Interop.Excel.Application
excel = New Microsoft.Office.Interop.Excel.Application
Dim tmpWorkbooks As Workbooks
tmpWorkbooks = excel.Workbooks
Dim wb As Microsoft.Office.Interop.Excel.Workbook
wb = tmpWorkbooks.Open(pathOfExcelFile)
excel.Visible = False
wb.Activate()
wb.ExportAsFixedFormat(XlFixedFormatType.xlTypePDF, fileName, , , , 1, 1, False, )

In Excel 2010 you can use this VBA code:
ActiveSheet.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:="C:\Temp\Workbook1.pdf", _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=True, _
OpenAfterPublish:=False
Of course you need to set Filenameto the correct path for your machine, and as it uses ActiveSheet I suppose you need to iterate through your sheets if you have more than one in your workbooks. See the MSDN for more details on the ExportAsFixedFormat function.

Related

User-defined type not defined vb6

I am attempting to 'save' the context of a text box in vb6 to a *.ini file, so that it can be used in a later part of the program. (i.e. the user would enter something into the text box, then later in the program, a label would appear with the user-entered, saved information).
I used the following code which I copied from the source of someone else's program, however it hasn't worked:
Dim fsys As New FileSystemObject
Dim outstream As TextStream
Dim write1 As String
Dim val1 As String
val1 = Text1.Text
inisettings = App.Path & "\Variables.ini"
Set outstream = fsys.OpenTextFile(inisettings, ForWriting, False, TristateFalse)
outstream.WriteLine (val1)
Set outstream = Nothing
This is the result:
Does anyone have any way to save data for later?
FileSystemObject lives inside an external library, to use it click Project then References and tick Microsoft Scripting Runtime.
You don't actually need to do any of that, the code below uses VB's built-in functionality to write a file.
Dim hF As Integer
hF = FreeFile()
Open App.Path & "\Variables.ini" For Output As #hF
Print #hF, val1
Close #hF
You must declare TristateFalse and give it a value like 0, 1 or 2.
You can take a look at this link: https://msdn.microsoft.com/en-us/subscriptions/bxw6edd3(v=vs.84).aspx
The reason why you are getting this error is because you don't have a reference to the Microsoft Scripting Runtime library. Follow the below instructions while in your VB6 project:
From the top menu, click on Project > References.
From the list, check the item entitled "Microsoft Scripting Runtime".
Click OK.
This will resolve your immediate error however your code still has some other issues. First off, you forgot to declare the variable inisettings. I am going to assume that you will want to always overwrite the entire file each time you update the INI file so you want to use the method CreateTextFile instead of OpenTextFile.
Dim fsys As New FileSystemObject
Dim outstream As TextStream
Dim write1 As String
Dim val1 As String
Dim inisettings As String
val1 = Text1.Text
inisettings = App.Path & "\Variables.ini"
Set outstream = fsys.CreateTextFile(inisettings, True, False)
Call outstream.WriteLine(val1)
Set outstream = Nothing
Good luck!

Open EML file in Outlook using Add-In?

Using Outlook Add-In (VSTO) can I open an EML file from disk and "display" it?
I've tried this...
Dim filename As String = "c:\test\_test.eml"
Dim mail As Outlook.MailItem = CType(Globals.ThisAddIn.Application.Session.OpenSharedItem(filename), Outlook.MailItem)
mail.Display()
But Outlook throws an exception saying path is not valid even though it is.
Any idea?
OpenSharedItem does not work with EML files.
Outlook Object Model would not let you access EML files. You can either
Parse the EML file (or use an available component), create new item in Outlook and set all properties one at a time
If you were using C++ or Delphi, you could have used IConverterSession MAPI interface to import the data
If using Redemption is an option, you can use something like the following (off the top of my head):
dim Session as Redemption.RDOSession = CreateObject("Redemption.RDOSession")
Session.MAPIOBJECT = Me.Application.Session.MAPIOBJECT
dim Drafts as Redemption.RDOFolder = Session.GetDefaultFolder(olFolderDrafts)
dim mail as Redemption.RDOMAil = Drafts.Items.Add
mail.Sent = true
mail.Import "c:\temp\test,eml", 1024 'olRfc922
mail.Save
'now reopen in OOM
dim oMail as Outlook.MailItem = Me.Application.Session.GetItemFromID(mail.EntryId)
dim forwardedMail as Outlook.MailItem = oMail.Forward
forwardedMail.Display()

Error when creating MS Excel docs with VB 2010

I'm having some trouble with looping and creating MS Excel docs, code snippet below
Private Sub selectedRowsButton_Click( _
ByVal sender As Object, ByVal e As System.EventArgs) _
Handles selectedRowsButton.Click
Dim selectedRowCount As Integer = _
DataGridView1.Rows.GetRowCount(DataGridViewElementStates.Selected)
If selectedRowCount > 0 Then
Dim sb As New System.Text.StringBuilder()
Dim objexcel As New Excel.Application
Dim i As Integer
Dim FACode As Integer
Dim Sitename As Integer
Dim Sitecode As Integer
Dim Address As Integer
Dim City As Integer
Dim State As Integer
Dim ZIP As Integer
FACode = 1
Sitename = 5
Sitecode = 2
Address = 6
City = 7
State = 9
ZIP = 10
Dim xlWorkbook As Excel.Workbook
xlWorkbook = objexcel.Workbooks.Open("template path")
For i = 0 To selectedRowCount - 1
objexcel.Visible = True
objexcel.Range("B2").Value = DataGridView1.SelectedCells(Sitename).Value.ToString()
objexcel.Range("B3").Value = DataGridView1.SelectedCells(Sitecode).Value.ToString()
objexcel.Range("B5").Value = DataGridView1.SelectedCells(FACode).Value.ToString()
Dim thisfile As Object
thisfile = objexcel.Range("B5").Value & "." & _
objexcel.Range("B3").Value & "." & "otherstring" & "." & "otherstring2" & "." & ".xls"
With objexcel
xlWorkbook.SaveAs(Filename:="c:\test\" & thisfile)
'~~> Close the Excel file without saving
xlWorkbook.Close(False)
End With
Next i
End If
I'm getting the error Exception from HRESULT: 0x800A03EC for the statement
objexcel.Range("B2").Value = DataGridView1.SelectedCells(Sitename).Value.ToString()
IF I select only one row of my DataGrid before creating the program works fine, it is when I select multiple rows that this error occurs. Since I'm creating the program specifically for multiple row selections I'm stumped as to where I've gone wrong. Any help or pointers appreciated, Thanks!
Two things
You have declared objexcel As Excel.Application so you shouldn't use objexcel.Range("B2").Value. Use xlWorkbook.Range("B2").Value. Change it everywhere in your code.
You cannot use SaveAs like that. See the snapshot below. If you want to save as xls file then you have to use FileFormat:=56
See this code example
'~~> Save As file
xlWorkbook.SaveAs(Filename:="c:\test\" & thisfile, FileFormat:=56)
If you do not specify the file format then you will get an error message when you open the file after opening.
You might want to look at this link on how to automate Excel from VB.Net
Topic: VB.NET and Excel
Link: http://www.siddharthrout.com/vb-dot-net-and-excel/
I am not too sure what you exactly are trying to do with the DGV. Like Sean mentioned you are not incrementing the values. If you can post a snapshot of how your DGV looks and how your Excel file should look after the export then we can help you in a much better way :)

How to access the database from the other system or server?

Using VB 6
How to access the database from the other system or server?
Code
Cn.ConnectionString = "Provider=Microsoft.jet.oledb.4.0; Data Source=" & _
App.Path & "\DC-CS.MDB"
Cn.Open
I don’t want to give the connection directly in my code, I want to select a connection and *.mdb file from the other system or same system or server.
What type of control I have to use in VB for connection testing and mdb file selection from the other system or server?
First thing I want to select a connection, if connection tested, then I want to select a *.mdb file from other system or server. How can I select a connection and *.mdb file in VB 6.
Please need VB 6 Code Help
You can use the Data Link Properties dialog to define an OLE DB connection string. You can start out by predefining the Provider and other attributes, and then let the user browse for an MDB file and choose it if you have predefined Jet 4.0 as the Provider.
Once this selection has been made you can persist the connection as a .UDL (Universal Data Link) file. UDLs were what replaced DSNs a long, long time ago. I'm amazed they get so little use.
Here is some sample code that lets your program specify a UDL and a default path for the user to browse for an MDB file. If the UDL does not exist, it opens the Data Link Properties dialog so the user can choose an MDB, and lets them Test Connection from that dialog before Oking or Canceling their settings. Once it has the connection fully defined it persists it as a .UDL file and opens the Connection object.
If the UDL file exists it opens the Connection using the specs in the UDL.
The key here is the DbOpenPromptSave() function.
'Requries references to:
' Microsoft ActiveX Data Objects x Library (x >= 2.5)
' Microsoft OLE DB Service Component 1.0 Type Library
Private Function DbOpenPromptSave( _
ByVal Conn As ADODB.Connection, _
ByVal UDLPath As String, _
Optional ByVal MDBSearchStartPath As String = "") As Boolean
'Returns True if user cancels the dialog.
On Error Resume Next
GetAttr UDLPath
If Err.Number Then
'No UDL, we need to prompt the user then create one.
On Error GoTo 0
Dim dlkUDL As MSDASC.DataLinks
Set dlkUDL = New MSDASC.DataLinks
Conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" _
& "Persist Security Info=False;" _
& "Jet OLEDB:Engine Type=5;" _
& "Data Source=" & MDBSearchStartPath & "\;" _
& "Window Handle=" & CStr(Me.hWnd)
If Not dlkUDL.PromptEdit(Conn) Then
DbOpenPromptSave = True
Exit Function
End If
'Use a Stream as Unicode writer. Using a relative path to save
'respects the Current Directory of the process.
Dim stmUDL As ADODB.Stream
Set stmUDL = New ADODB.Stream
With stmUDL
.Open
.Type = adTypeText
.Charset = "unicode"
.WriteText "[oledb]", adWriteLine
.WriteText "; Everything after this line is an OLE DB initstring", _
adWriteLine
.WriteText Conn.ConnectionString
.SaveToFile UDLPath, adSaveCreateOverWrite
.Close
End With
Conn.Open
Else
Conn.Open "File Name=" & UDLPath
End If
End Function
Private Function DbActions() As Boolean
'Returns True on cancel.
Dim connDB As ADODB.Connection
Set connDB = New ADODB.Connection
If DbOpenPromptSave(connDB, "sample.udl", App.Path) Then
MsgBox "User canceled!"
DbActions = True
Exit Function
End If
DoDbOperations connDB 'Whatever you need to do until closing.
connDB.Close
End Function
The DbActions() function is simply an example of calling DbOpenPromptSave() to open the database. This function opens the database, calls DoDbOperations() (not shown) to actually work with the open database, and then closes the database Connection.
This example uses a relative path (current directory, usually the same as App.Path) for sample.udl and sets the MDBSearchStartPath (where the Select Access database dialog opens) to App.Path (because this dialog defaults to where the last CommonDialog had been opened).
So in other words...
It looks for/saves the UDL sample.udl in CD (usually App.Path), and the MDB selection dialog opens in App.Path. Whew.
I suppose just passing CurDir$() might have been clearer in this case.
I hope this comes close to what you were requesting, it was a little vague.
The MDB selection subdialog the user opens is pretty much a standard CommonDialog.ShowOpen dialog. The user should be able to browse for the MDB file on any drive including file shares on remote systems.
RBarry is referring to the fact that you can "share" a particular folder on one computer, so that it is accessible to another computer.
If two computers are named computer1 and computer2, then computer2 can share a folder on it's C: drive giving it some name like "sharedfolder". Then computer1 can access that folder using the path "\\computer2\sharedfolder".
If an application on computer1 can't use that path, then you can "map" a drive letter (like F:) to the path "\\computer2\sharedfolder". Then it just looks like the F: drive on computer1.
Share your App.Path to the domain. Then on the other system, point it's App.Path to your share.
If you want to dynamically select your path and/or file, then use the FileOpen dialog/control.
As for code examples, I haven't used real VB6 in almost 5 years, so I do not have any true examples or anyway to make one. The closest I can come is Excel VBA 6.5. Here is an example of a VBA function that I use in Excel to browse for and open an Access database:
Public Function OpenDB() As Boolean
'Open the Database and indicate if successful'
If IsOpen Then
OpenDB = True 'we are already open'
Exit Function
End If
If sFile = "" Then sFile = GetSetting("YourAppName", "History", "DBName")
With Application.FileDialog(msoFileDialogFilePicker)
'specify the file open dialog'
.AllowMultiSelect = False
.Filters.Clear
.Filters.Add "Access Workbooks", "*.mdb"
.Filters.Add "All Files", "*.*"
.InitialFileName = sFile
.Title = "Open TIP Database"
.Show
If .SelectedItems.Count > 0 Then
sFile = .SelectedItems(1)
Else 'user canceled ...'
OpenDB = False
Exit Function
End If
End With
DB.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & sFile
On Error Resume Next
DB.Open
If Err.Number <> 0 Then
MsgBox "Error(" & Err.Number & "): " & Err.Description, vbOKOnly + vbCritical, "Error in OpenDB"
OpenDB = False
Exit Function
End If
'Opened ok, so finsh-up and exit'
OpenDB = True
SaveSetting "YourAppName", "History", "DBName", sFile
End Function
You will have to replace the "Application.FileDialog" with a reference to a VB Forms FileDialog control/component, which you should drop onto your VB from from the toolbox (its actually a component-control, so it's not really visible).
You should expect that it will have some differences because these are GUI features and the VB Forms GUI is radically different from the Excel GUI. So the properties & settings might be different and you'll have to play around with them or look them up in VB Help.
Note: the GetSetting and SaveSetting stuff is just saving the last file name and path used in the registry, so that it can use it as the default location for the next time.

Visual Studio: Printing all source files in a solution?

Is there a way to print all (*.cs) files in a solution at once, that is, without clicking on each of them and then hitting print?
From what I gather from a similar question asked elsewhere, this "feature" is not build into Visual Studio.
However it looks like MSDN has a macro you can use to print all of your code; perhaps you can use this, or something like it:
Sub PrintItemsInSelectedProject()
Dim proj As Project
Dim objProj As Object()
objProj = DTE.ActiveSolutionProjects
If objProj.Length = 0 Then
Exit Sub
End If
proj = DTE.ActiveSolutionProjects(0)
PrintItemsInSelectedProject(proj.ProjectItems)
End Sub
Private Sub PrintItemsInSelectedProject( _
ByVal projitems As ProjectItems)
Dim projitem As ProjectItem
For Each projitem In projitems
If (IsPrintableFile(projitem) = True) Then
If (projitem.IsOpen( _
EnvDTE.Constants.vsViewKindTextView)) Then
projitem.Document.PrintOut()
Else
Dim doc As Document
doc = projitem.Open( _
EnvDTE.Constants.vsViewKindTextView).Document
doc.PrintOut()
doc.Close(vsSaveChanges.vsSaveChangesNo)
End If
End If
PrintItemsInSelectedProject(projitem.ProjectItems)
Next
End Sub
Function IsPrintableFile( _
ByVal projItem As ProjectItem) As Boolean
Dim fileName As String
Dim extensions As _
New System.Collections.Specialized.StringCollection
' If you add a file to your project that is of
' a type that can be printed,
' then add the extension of that
' file type to this list.
Dim exts As String() = {".cs", ".vb", _
".aspx", ".xsd", ".xml", ".xslt", _
".config", ".htm", ".html", ".css", _
".js", ".vbs", ".wsf", ".txt", ".cpp", _
".c", ".h", ".idl", ".def", ".rgs", ".rc"}
extensions.AddRange(exts)
fileName = projItem.FileNames(1)
Return extensions.Contains( _
System.IO.Path.GetExtension(fileName).ToLower())
End Function
Putting aside the fun comments from tree-huggers, let's assume you want to printout the Visual Studio solution as PDF (and we won't ask what you do with it later).
For people who use VisualStudio there is a very nice program that used to be sold but is now available to download for free, called PrettyCode.Print for .NET 2.0. It is available for download here (the company retired the product).
It reads in a VisualStudio project (works with VS2005, VS2008 and VS2010) and let one print a selection of files with various printing options. It does a pretty decent job.
You can download PrettyCode.Print for .NET 2.0 (VS2008 and VS2005) in:http://pan.baidu.com/wap/shareview?&shareid=3968547697&uk=286220058&dir=%2FSoftz&page=1&num=20&fsid=1117386981714891&third=0
In my computer work fine with Visual Studio 2013.
Use powershell to print all *.cs files.
First get list of all files
$files = Get-Childitem -Path C:\Users\David\source\repos\ConsoleApp -Exclude AssemblyInfo.cs, Program.cs -Include *.cs -Recurse
When your happy with list
foreach ($file in $files){ Get-Content $file.FullName |Out-printer}

Resources