i'm new to vb.net, and i want to open an existing excel file, and insert an image to a specific cell, such as 'C16' for exemple.
It's been three days and i'm searching about this topic, but what i found was just creating a new excel file and insert a picture to it.
Anybody can help?
The code can be used is like this:
ActiveSheet.Pictures.Insert(pathForPicture & "\" & pictureName & ".jpg").Select 'Path to where pictures are stored
For more reading from this site: VBA to insert embeded picture excel
How to insert a picture into Excel at a specified cell position with VBA
I've already found a solution:
please find it below
workbook = APP.Workbooks.Open(filepath)
worksheet = workbook.Worksheets("name of the excel sheet")
worksheet.Visible = True
Dim pic1 As String = "picture path"
worksheet.Range("I51:I51").Select()
I51 is the cell where i want my picture
worksheet.PageSetup.Zoom = False
worksheet.PageSetup.FitToPagesWide = 1
worksheet.PageSetup.FitToPagesTall = 1
Dim opicture1 As Object
opicture1 = worksheet.Pictures.Insert(pic1)
I would like to provide my codes.
Dim picPath As String = "C:\..."
Dim _Left = xlWorkSheet.Range(WorkSheet.Cells(i, j).Address).Left
Dim _Top = xlWorkSheet.Range(WorkSheet.Cells(i, j).Address).Top
Dim _Width = xlWorkSheet.Range(WorkSheet.Cells(i, j).Address).Width
Dim _Height = xlWorkSheet.Range(WorkSheet.Cells(i, j).Address).Height
WorkSheet.Shapes.AddPicture(picPath, False, True, _Left, _Top, _Width, _Height)
picPath is the path of the image you want to insert.
(i,j) is the index of the cell where you want to insert an image.
Related
I have trouble with the following tasks in excel VBA:
At my work, we use a document management platform called TeamShare: [https://www.lector.dk/en/products/]
I want to create a code in VBA, that loops over a range of links to this document management platform in my workbook, ie. loops over other workbooks, opens them and then copies a specified sheet to my current workbook.
I have tried putting together bits of codes from other sites, and the code works just fine when i run it in break mode. However, when I run the code all at once, the Excel program reopens, such that the current workbook cannot "communicate" with the opened workbook and I end up in an infinity loop (so no direct error message).
This is the code that only works in break mode:
Dim wbCopyTo As Workbook Dim wsCopyTo As Worksheet Dim i As Long Dim Count As Long Dim WBCount As Long Dim LastRow As Long Dim wb As Workbook Dim ws As Worksheet Dim URL As String Dim IE As Object Dim doc As Object Dim objElement As Object Dim objCollection As Object
Set wbCopyTo = ActiveWorkbook Set wsCopyTo = ActiveSheet
LastRow = wsCopyTo.Range("B" & Rows.Count).End(xlUp).Row
For i = 2 To LastRow
Set IE = CreateObject("InternetExplorer.Application")
IE.Visible = True
The purpose of this piece of code is to get the DocID
A = InStr(wsCopyTo.Range("B" & i), "documentid=") + Len("documentid=")
B = InStrRev(wsCopyTo.Range("B" & i), "&")
DocID = Mid(wsCopyTo.Range("B" & i), A, B - A)
'Get URL
URL = wsCopyTo.Range("B" & i)
'Count number of open workbooks
WBCount = Workbooks.Count
With IE
New is the comman that opens excel sheet. This works as planned in breakmode, however the excel program reopens when i run the code all at once. I have tried other commandos here: "Workbooks.Open", I couldn't get this one to open the file and "Application.FollowHyperlink" only worked in break mode too, however, much much slower
.Navigate URL
'This was my solution to how to stop the rest of the code from executing until the new workbook has loaded.
Do Until Workbooks.Count = WBCount + 1: Loop
End With
'Unload IE
Set IE = Nothing
Set objElement = Nothing
Set objCollection = Nothing
'So in order to activate the workbook from the URL, I am looping over all my open workbooks and matching them on their unique Document ID. I found that the workbook from the URL wasn´t the "active workbook" per default.
For Each book In Workbooks If Mid(book.Name, 12, Len(DocID)) = DocID Then
book.Activate
Set wb = ActiveWorkbook
Set ws = ActiveSheet
End If
Next book
Here i copy the desired sheet to my initial workbook
wb.Worksheets("SpecificSheetIWantToCopy").Copy After:=wbCopyTo.Worksheets("Sheet1") wbCopyTo.Sheets(ActiveSheet.Name).Name = DocID
Next i
End Sub
I am using excel 2010.
I hope you can help me resolve this problem. Please ask if you need any more information, that i haven´t provided.
Thanks in advance.
I am having trouble with the Open XML SDK opening and saving word documents.
I am using the following code (VB.Net):
Try
'Set Path
Dim openPath As String = "../Documents/" & worddoc
Dim savePath As String = "\\web-dev-1\HR_Documents\" & worddoc
Using doc As WordprocessingDocument = WordprocessingDocument.Open("/Documents/" & worddoc, True)
'Employee Name Insert
'Find first table in document
Dim tbl1 As Table = doc.MainDocumentPart.Document.Body.Elements(Of Table).First()
'First Row in tbl
Dim row As TableRow = tbl1.Elements(Of TableRow)().ElementAt(0)
'Find first cell in row
Dim cell As TableCell = row.Elements(Of TableCell)().ElementAt(0)
'Insert selected Employee Name
Dim p As Paragraph = cell.Elements(Of Paragraph)().First()
Dim r As Run = p.Elements(Of Run)().First()
Dim txt As Text = r.Elements(Of Text)().First()
txt.Text = ddlEmployeeList.SelectedItem.Text
'Save File
'Supervisor Name Insert
'Find second table in document
Dim tbl2 As Table = doc.MainDocumentPart.Document.Body.Elements(Of Table).First()
'First Row in tbl
Dim row2 As TableRow = tbl2.Elements(Of TableRow)().ElementAt(0)
'Find first cell in row
Dim cell2 As TableCell = row2.Elements(Of TableCell)().ElementAt(0)
'Insert selected Employee Name
Dim p2 As Paragraph = cell2.Elements(Of Paragraph)().First()
Dim r2 As Run = p2.Elements(Of Run)().First()
Dim txt2 As Text = r2.Elements(Of Text)().First()
txt2.Text = ddlSupervisorList.SelectedItem.Text
End Using
Return 1
Catch ex As Exception
Return Nothing
End Try
The trouble starts on the first using statement. It throws the following error:
Could not find a part of the path 'C:\Documents\Hourly_Employee_Performance_Review .docx
I have placed the word documents in a folder of the ASP.NET site called Documents. I also have created a public share on the dev server to see if maybe that would help.
The problem is that it doesn't use the supplied path variable. I have gone through the documentation for OPEN XMl SDK but all it talks about is the Using Statement and its need and use for it.
Can anyone tell me, show me, or point to a site that has examples of how to set both the open path and save path?
You need a path to the file which is based on the filesytem, not a URL. You can do that with
Dim openPath As String = Path.Combine(Server.MapPath("~/Documents"), worddoc)
And then to open the file:
Using doc As WordprocessingDocument = WordprocessingDocument.Open(openPath, True)
It appears that you will need to do the same for the location to save to, but you didn't say if "\\web-dev-1" is a different server; if it were that would need other considerations.
(Not tested, some typos may exist. You will need an Imports System.IO.)
So I have searched for a about 2 days now and while I can find a lot of examples of how to get an Excel worksheet into a gridView, none of them work for me.
This is the goal: I need to read an Excel file, has one worksheet in it and should always be one worksheet in it, into a GridView in ASP.NET website and I am using VB.Net in code behind file.
I tried one way trying to use the Schema of the table name (To get the sheet names) but no matter what the sheet name was it always came back as 'Algrip' of which there is NO sheet with that name in any of the workbooks I an testing with.
So I scrapped that and am now using the this code: (Which does get the job done, sort of)
'Setup Variables
Dim xlConnStr As String = ""
Dim FileName As String = Path.GetFileName(FileUpload1.PostedFile.FileName)
Dim Extension As String = Path.GetExtension(FileUpload1.PostedFile.FileName)
Dim FolderPath As String = ConfigurationManager.AppSettings("FolderPath")
Dim sheetname As String = InputBox("Enter Sheetname: ", "Excel Worksheet name")
'Adjust Sheetname
sheetname = sheetname + "$"
'Set Connection based on Excel File Extension
Select Case Extension
Case ".xls"
'Excel 97-03
xlConnStr = ConfigurationManager.ConnectionStrings("Excel03ConString").ConnectionString
Case ".xlsx"
'Excel 07-Forward
xlConnStr = ConfigurationManager.ConnectionStrings("Excel07ConString").ConnectionString
End Select
xlConnStr = String.Format(xlConnStr, FolderPath & FileName)
Dim connXL As New OleDb.OleDbConnection(xlConnStr)
pnlFileInfo.Visible = True
connXL.Open()
Using xlCmd As New OleDbCommand
xlCmd.CommandType = CommandType.Text
xlCmd.CommandText = ("Select * From [" + sheetname + "]")
xlCmd.Connection = connXL
Using xlDS As New DataSet()
Using xlDA As New OleDbDataAdapter(xlCmd)
xlDA.Fill(xlDS)
gvExcelFile.DataSource = xlDS
gvExcelFile.DataBind()
End Using
End Using
End Using
connXL.Close()
Now my problem is this; On the follwoing line:
xlCmd.CommandText = ("Select * From [" + sheetname + "]")
If I do not have the left and right brackets, because the some sheet names have spaces in them, I get a query error. But if I add the brackets it prompts me twice for the sheet name. For the life of me I can not figure out why.
I have put a break point in on the line listed above and checked the value of the variable sheetname and it is correct but for some reason I get prompted again.
Does anyone have any idea as to why it is doing this? What am I missing? What I ideally wanted was to be able to read the sheet name and feed it to the line with the select statement so that there is no user action required but all I ever got that way was the same bad sheet name 'Algrip'.
The Excel sheet is an xls file but can be saved as xlsx if it would help.
I am open to re-doing the code if i can get it to read the sheet name dynamically.
Thanks for any help!!
try storing the whole command in a variable then assign it to the xlCmd.CommandText using the OleDbCommand constructor
Dim sheetname As String = InputBox("Enter Sheetname: ", "Excel Worksheet name")
sheetname = sheetname & "$"
Dim strQuery As String = "Select * From [" & sheetname & "]"
...
Using xlCmd As New OleDbCommand(strQuery ,connXL)
Using xlDS As New DataSet()
Using xlDA As New OleDbDataAdapter(xlCmd)
xlDA.Fill(xlDS)
gvExcelFile.DataSource = xlDS
gvExcelFile.DataBind()
End Using
End Using
End Using
connXL.Close()
could someone help me with this error??
I tried to save excel file using EPPlus
[IOException: The process cannot access the file 'C:\Users\Julian\Downloads\EmployeeMaster.xls' because it is being used by another process.]
here is my code :
Dim conn As New ConnectionVB
Dim newfile As FileInfo = NewFileInfo("C:\\Users\\Julian\\Downloads\\EmployeeMaster.xls")
Using p As ExcelPackage = New ExcelPackage(newfile)
SetWorkBookProperties(p)
conn.connect()
Dim ws As ExcelWorksheet = CreateSheet(p, "EmnployeeMaster")
Dim dt As New DataTable
Dim connString As String
connString = "Select * from EmployeeMaster"
dt = conn.openDataTable(connString)
Dim rowIndex As Integer
rowIndex = 2
CreateHeader(ws, rowIndex, dt)
CreateData(ws, rowIndex, dt)
Dim bin As Byte()
bin = p.GetAsByteArray()
Dim path As String
path = "C:\\Users\\Julian\\Downloads\\EmployeeMaster.xls"
File.Delete("C:\\Users\\Julian\\Downloads\\EmployeeMaster.xls")
Dim stream As Stream = File.Create(path)
File.WriteAllBytes(path, bin) <- I got the error here
Start(path)
stream.Close()
End Using
Appriciate all help/advice with this error
Regards Siekh
As from your Error shows: EmployeeMaster.xls file is being used by another process.
Your code DryRun:
In your EmployeeMaster.xls file you make another new sheet name as EmnployeeMaster and then you create Header, and Data in this sheet.
problem arise when you write to file. you have to just save WorkSheet by doing .
because just open your .xls file with the help of EPPlusPackage and then by code Add your custom sheet in .xls file and just save.
p.Save(); // you need to save this temporary sheet.
Problems may be:
EPPLUS cannot open xls files, only xlsx files.
Why you delete File.
solution: you can rename and then move.
EPPlus hold your file when you instantiate object for ExcelPackage(with the same Path)
Two Problems:
EPPlus does not support xls files.
For debugging why the file is used, I recommend using SysInternal's "process explorer", you can find it here.
I'm looking for options to fill a Word Document from either Visual Basic, or Visual C#. I'm currently using merge fields, and the code below to fill specific fields in a Word Document, but now I've run into a situation where I need tabular data pushed to MS Word. Is there anyway to take data from a grid view (number of rows is dynamic), and import it into a Word Document Table using a merge field or something of that sort? I have to maintain the format of my template doc, and would like to be able to control the layout of the page ..
Dim templateDoc As String = Server.MapPath("\Userfiles\docs\" & location)
Dim mergePath As String = Server.MapPath("\App_Data\Temp\")
Dim mergeFileName As String = location.Replace("/", "_") & ".docx"
Dim mergeDoc As String = mergePath & "\" & mergeFileName
File.Copy(templateDoc, mergeDoc, True)
Using pkg As Package = Package.Open(mergeDoc, FileMode.Open, FileAccess.ReadWrite)
Dim uri As Uri = New Uri("/word/document.xml", UriKind.Relative)
Dim part As PackagePart = pkg.GetPart(uri)
Dim xmlMainXMLDoc As XmlDocument = New XmlDocument()
xmlMainXMLDoc.Load(part.GetStream(FileMode.Open, FileAccess.Read))
Dim innerXml As String = xmlMainXMLDoc.InnerXml _
.Replace("«Corporate Legal Name»", businessName) _
.Replace("«Address 1»", mailingAddress1) _
.Replace("«Address 2»", mailingAddress2) _
.Replace("«City»", city)
xmlMainXMLDoc.InnerXml = innerXml
Using partWriter As New StreamWriter(part.GetStream(FileMode.Open, FileAccess.Write))
xmlMainXMLDoc.Save(partWriter)
End Using
pkg.Close()
End Using
You can write out in HTML and save it with a .doc extension and Word will handle it gracefully.
Just like my answer for your question regarding Excel, Office writer will work for you here too!