Excel 2010 Add-In having issues with saving picture clipboard to file - vb.net

I'm trying to make an add in in vs2010 for Excel 2010 that copies an image to clipboard and then saves it.
The add in has a button which runs the following code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As Microsoft.Office.Tools.Ribbon.RibbonControlEventArgs) Handles Button1.Click
Dim app As Excel.Application = Globals.ThisAddIn.Application
Dim desktopFolder As String = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
Dim fileName As String = "D:\testaddin\test.jpg"
Dim activeWorksheet As Excel.Worksheet = Globals.ThisAddIn.Application.ActiveWorkbook.ActiveSheet
'Dim currentCell As Excel.Range = Globals.ThisAddIn.Application.Selection
Dim pic As Excel.Shape = activeWorksheet.Shapes.Item("Picture 1")
pic.CopyPicture()
If Not System.Windows.Forms.Clipboard.GetDataObject() Is Nothing Then
Dim oDataObj As IDataObject = System.Windows.Forms.Clipboard.GetDataObject()
If oDataObj.GetDataPresent(System.Windows.Forms.DataFormats.Bitmap) Then
Dim oImgObj As System.Drawing.Image = oDataObj.GetData(DataFormats.Bitmap, True)
oImgObj.Save("d:\Test.jpeg", System.Drawing.Imaging.ImageFormat.Jpeg)
End If
End If
End Sub
The code compiles just fine but when I press the button nothing happens.
One thing i know for sure is that the code DOES copy the picture to the clipboard as i checked that in mspaint.
How can I make the clipboard to be saved to jpeg?

Related

declaring New Microsoft.Office.Interop.Excel.Application outside of Sub makes the VSTO COM addin to freeze during loading

I have created an Excel COM add in which opens a windows form from a ribbon button. I want to populate the combobox using data from an external excel spreadsheet as well as populate the textboxes based on the selected name.
The part of the form where this applies
when placing the block of code:
Dim ExcelApp = New Microsoft.Office.Interop.Excel.Application ' this is causing the issue
Dim ClientListBook = ExcelApp.Workbooks.Open("C:\Users\SoftwareDev\Desktop\ASSETS\MasterFile.xlsx")
Dim ClientListSheet = ClientListBook.Sheets(1)
below the Public Class Form1 as seen below:
Imports Microsoft.Office.Interop.Excel
Public Class Form1
Dim ExcelApp = New Microsoft.Office.Interop.Excel.Application ' this is causing the issue
Dim ClientListBook = ExcelApp.Workbooks.Open("C:\Users\SoftwareDev\Desktop\ASSETS\MasterFile.xlsx")
Dim ClientListSheet = ClientListBook.Sheets(1)
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cmbClientName.SelectedIndexChanged
End Sub
it causes the Add in to freeze
But when Placing the same block of code into the Sub Form1_Load and Sub ComboBox1 as seen below, the add in works although it is very slow and i suspect it is an incorrect implementation.
THIS IS THE WORKING FULL CODE FOR THE FORM:
Imports Microsoft.Office.Interop.Excel
Public Class Form1
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cmbClientName.SelectedIndexChanged
Dim ExcelApp = New Microsoft.Office.Interop.Excel.Application ' this is causing the issue
Dim ClientListBook = ExcelApp.Workbooks.Open("C:\Users\SoftwareDev\Desktop\ASSETS\MasterFile.xlsx")
Dim ClientListSheet = ClientListBook.Sheets(1)
Dim iStartedRow As Integer
Dim iTotalRows As Integer
' count the number of rows in the worksheet
iTotalRows = ExcelApp.ActiveWorkbook.Sheets(1).Range("a1").CurrentRegion.Rows.Count
' populates the textboxes using clientList data
For iStartedRow = 2 To iTotalRows
If Me.cmbClientName.Text = ClientListSheet.Cells(iStartedRow, 1).text Then
Me.txtSal.Text = ClientListSheet.Cells(iStartedRow, 4).text
Me.txtInvMan.Text = ClientListSheet.Cells(iStartedRow, 5).text
End If
Next
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim ExcelApp = New Microsoft.Office.Interop.Excel.Application ' this is causing the issue
Dim ClientListBook = ExcelApp.Workbooks.Open("C:\Users\SoftwareDev\Desktop\ASSETS\MasterFile.xlsx")
Dim ClientListSheet = ClientListBook.Sheets(1)
Dim StartedRow As Integer
Dim TotalRows As Integer
' clear any existing data
Me.cmbClientName.Items.Clear()
' count the number of rows in the worksheet
TotalRows = ExcelApp.ActiveWorkbook.Sheets(1).Range("a1").CurrentRegion.Rows.Count
' create a loop to add data into combobox
For StartedRow = 2 To TotalRows
Me.cmbClientName.Items.Add(ClientListSheet.Cells(StartedRow, 1).Text)
Next
End Sub
End Class
Please would you let me know how i can correctly implement this and if it would be better and faster to use Microsoft Access database instead. I am new to VSTO COM add ins and VB.Net, this is my first project so i understand that my implementation may be suboptimal and will appreciate all feedback.
Thank you
If you declare and initialize these variables on the class level, they are created when the constructor runs.
There is absolutely no reason to initialize them immediately - you can declare them on the class level, but create them only when needed
Moreover, if your code is running in a VSTO addin, there is absolutely no reason to create an instance of the Excel.Application object - it is already available to you.
Hardcoding the file path is obviously also a problem...
Public Class Form1
Dim ExcelAppe
Dim ClientListBook
Dim ClientListSheet
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ExcelApp = Globals.ThisAddin.Application
ClientListBook = ExcelApp.Workbooks.Open("C:\Users\SoftwareDev\Desktop\ASSETS\MasterFile.xlsx")
ClientListSheet = ClientListBook.Sheets(1)

vb.net chart using data from excel

I am trying to just do a simple example before I do a more advanced project and I cant figure out how to use excel data from cells in a chart in vb.net. When I look it up online all I can find is database to vb.net or from vb.net to excel chart. Was going off of this for awhile but none of it is working http://www.siddharthrout.com/2011/10/18/charting-with-vb-net-2010/
Then I tried the below code with no luck, Get run time error converting range to string
Imports Excel = Microsoft.Office.Interop.Excel
Public Class Form1
Dim appXL As Excel.Application
Dim wbsXL As Excel.Workbooks
Dim wbXL As Excel.Workbook
Dim Rangex As Excel.Range
Dim Rangey As Excel.Range
Public Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
appXL = CreateObject("Excel.Application")
appXL.Visible = True
wbsXL = appXL.Workbooks
wbXL = wbsXL.Open("C:\Users\aholiday\Desktop\Data.xlsx")
Rangey = wbXL.Range("A1:A2")
Rangex = wbXL.Range("B1:B2")
With chtTest
.Series("Series1").YValueMembers = Rangey
.Series("Series1").XValueMember = Rangex
End With
End Sub
End Class
Can anyone show me a basic example using 2 cells for the x and 2 cells for the y axis data.
I may not understand what you are asking. I was not able to get your example to work. Therefore, I just used half the code from this page and half the code from the other page and I got something to work. Yet, because I could not get your code to run I am not sure if this is what you are asking for.
'http://ask.brothersoft.com/how-to-use-an-excel-insertable-object-in-visual-basic-160217.html
'http://vb.net-informations.com/excel-2007/vb.net_excel_create_chart.htm
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles
Button1.Click
Dim XLSApp As New Excel.Application
XLSApp.Visible = True
Dim XLSWbks As Excel.Workbooks = XLSApp.Workbooks
Dim XLSWbk As Excel.Workbook = XLSWbks.Add
Dim XLSShts As Excel.Sheets = XLSWbk.Worksheets
Dim XLSSht As Excel.Worksheet = XLSShts("Sheet1")
XLSSht.Range("A1").Value = "1"
XLSSht.Range("A2").Value = "2"
XLSSht.Range("B1").Value = "1"
XLSSht.Range("B2").Value = "2"
'create chart
Dim chartPage As Excel.Chart
Dim xlCharts As Excel.ChartObjects
Dim myChart As Excel.ChartObject
Dim chartRange As Excel.Range
xlCharts = XLSSht.ChartObjects
myChart = xlCharts.Add(10, 80, 300, 250)
chartPage = myChart.Chart
chartRange = XLSSht.Range("A1", "B2")
chartPage.SetSourceData(Source:=chartRange)
chartPage.ChartType = Excel.XlChartType.xlColumnClustered
End Sub

How to close a word document

When I run this application, the document opens fine but it doesn't close and leaves the document open. How can I close the word doc properly?
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim AppWord = CreateObject("Word.Application")
Dim WordDoc = CreateObject("Word.Document")
Dim filename As String
Dim result As String
filename = "C:\Users\Business\Desktop\Test.docx"
WordDoc = AppWord.Documents.Open(filename)
txtFileContents.Text = WordDoc.Content.Text
WordDoc.Close()
End Sub
Perhaps, you want to close the Word app at the end? Try this:
AppWord.Quit
use the shell function to close it (taskkill)

Embed multiple excel files in a word document, displayed as icons

I am able to copy a single excel file into a word document, displayed as an icon. But when i select multiple files from a folder, what happens is each of the files get copied into a new word document. In other words, I am unable to embed multiple files at a time into a single word document.
Also here in my code i have to create a bookmark from begining into the word document. I want to create the bookmark in the word document dynamically through code.
Could anyone please guide me how i can create bookmarks dynamically through code and also how can i embed many files at a time into a single word document.
Here is my working code that embeds only one file at a time.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim ofd As New OpenFileDialog
ofd.InitialDirectory = My.Computer.FileSystem.SpecialDirectories.MyDocuments
ofd.Filter = "Excel Files (*.xls;xlsx)|*.xls;xlsx"
ofd.FilterIndex = 2
ofd.RestoreDirectory = True
ofd.Multiselect = True
Dim Files As String = ofd.InitialDirectory
If ofd.ShowDialog() = DialogResult.OK Then
For Each Files In ofd.FileNames
Dim filename As String = ofd.FileName
Dim oWord As Word.Application = New Word.Application()
Dim oWordDoc As Word.Document = oWord.Documents.Open("C:\testing.doc", False)
Dim oMissing As Object = System.Reflection.Missing.Value
oWord.Visible = True
'ICON LABEL CAN BE THE NAME OF THE FILE,
'ITS THE NAME DISPLAYED BESIDES THE EMBEDDED DOCUMENT
Dim oIconLabel As Object = filename
'THE BOOKMARK WHERE THE FILE NEEDS TO BE EMBEDDED
Dim oBookMark As Object = "ssss"
'//THE LOCATION OF THE FILE
Dim oFileDesignInfo As Object = filename
'//OTHER VARIABLES
Dim oClassType As Object = "Word.Document.8"
Dim oTrue As Object = True
Dim oFalse As Object = False
'Dim oMissing As Object = System.Reflection.Missing.Value
Dim oIconFileName As Object = oMissing
'METHOD TO EMBED THE DOCUMENT
oWordDoc.Bookmarks.Item(oBookMark).Range.InlineShapes.AddOLEObject(oClassType, oFileDesignInfo, _
oFalse, oTrue, oIconFileName, oMissing, oIconLabel, oMissing)
Next
End If
End Sub
Your code to open a new word instance and load the document is within the loop - move it out of the loop so you only run it once.
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim ofd As New OpenFileDialog
ofd.InitialDirectory = My.Computer.FileSystem.SpecialDirectories.MyDocuments
ofd.Filter = "Excel Files (*.xls;xlsx)|*.xls;xlsx"
ofd.FilterIndex = 2
ofd.RestoreDirectory = True
ofd.Multiselect = True
Dim Files As String = ofd.InitialDirectory
If ofd.ShowDialog() = DialogResult.OK Then
Dim oWord As Word.Application = New Word.Application()
Dim oWordDoc As Word.Document = oWord.Documents.Open("C:\testing.doc", False)
Dim oMissing As Object = System.Reflection.Missing.Value
oWord.Visible = True
For Each Files In ofd.FileNames
'*************
'rest of code....
'*************
Next
End If
End Sub
Finally have done it successfully...Here is the working code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim ofd As New OpenFileDialog
ofd.InitialDirectory = My.Computer.FileSystem.SpecialDirectories.MyDocuments
ofd.Filter = "Excel Files (*.xls;xlsx)|*.xls;xlsx"
ofd.FilterIndex = 2
ofd.RestoreDirectory = True
ofd.Multiselect = True
Dim Files As String
If ofd.ShowDialog() = DialogResult.OK Then
Dim oWord As Word.Application = New Word.Application()
Dim oWordDoc As Word.Document = oWord.Documents.Open("C:\testing.doc", True)
Dim oBookmark As Object = oWordDoc.Bookmarks.Add("Bookmark")
Dim oMissing As Object = System.Reflection.Missing.Value
oWord.Visible = True
For Each Files In ofd.FileNames
'ICON LABEL CAN BE THE NAME OF THE FILE,
'ITS THE NAME DISPLAYED BESIDES THE EMBEDDED DOCUMENT
Dim oIconLabel As Object = Path.GetFileName(Files)
'//INCASE WE NEED THE EMBEDDED DOCUMENT TO BE DISPLAYED AS A SPECIFIC ICON,
'//WE NEED TO SPECIFY THE LOCATION OF THE ICON FILE
'//ELSE SET IT TO oMissing VALUE
'Dim oIconFileName As Object = "C:\\Document and Settings\\IconFile.ico"
'//THE LOCATION OF THE FILE
Dim oFileDesignInfo As Object = Files
'//OTHER VARIABLES
Dim oClassType As Object = "Word.Document.8"
Dim oTrue As Object = True
Dim oFalse As Object = False
'Dim oMissing As Object = System.Reflection.Missing.Value
Dim oIconFileName As Object = oMissing
'//METHOD TO EMBED THE DOCUMENT
oWordDoc.Bookmarks.Item(oBookMark).Range.InlineShapes.AddOLEObject(oClassType, oFileDesignInfo, _
oFalse, oTrue, oIconFileName, oMissing, oIconLabel, oMissing)
Next
End If
Me.Close()
End Sub

Can't access form1 from another class

I have a class called class1, in that class i wan;t to write something in a textbox in form1, but it won't let me access Form1.TextBox1.text, another problem is that it won't give me the save dialog in excel, but thats another problem.
How can i acces Form1 controls?
Form1 code
Public Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Call ThisDrawing.GetFilepath(True)
If Me.TextBox1.Text = "" Or Me.TextBox1.Text = "False" Then MsgBox("Er is geen geldige filenaam opgegeven")
End Sub
Class1 code
Public Shared Sub GetFilepath(ByVal hide As Boolean)
Dim Xl As New Excel.Application
Dim Filepath As String
Call ExcelKoppelen("Z:\test\test.xls")
Filepath = Xl.GetSaveAsFilename("", "Excel file", "*.xls")
Form1.TextBox1.text = Filepath
End Sub
Excelkoppelen code
Shared Sub ExcelKoppelen(ByVal Bestand As String)
Dim Xl As Excel.Application
Dim Filepath As String
Dim Workbook As Excel.Workbook
Dim Worksheet1 As Worksheet
Dim Worksheet2 As Worksheet
On Error Resume Next
Xl = GetObject(, "Excel.application")
If Err.Number Then
Information.Err.Clear()
Xl = CreateObject("Excel.application")
End If
Xl.Visible = True
Xl.ScreenUpdating = True
Workbook = Xl.Workbooks.Open(Bestand)
If Err.Number Then
Workbook = Xl.Workbooks.Open("Z:\test\test.xls")
Information.Err.Clear()
Workbook.SaveAs(Bestand)
End If
If Err.Number Then Exit Sub
On Error GoTo 0
Worksheet1 = Workbook.Worksheets.Item(1)
Worksheet2 = Workbook.Worksheets.Item(2)
Xl.Visible = False
End Sub
You can not access the controls in Form1 directly like that, create an object for Form1 as follows and get the controls by using the object.
Dim F as New Form1
F.TextBox1.text = Filepath