I have been unsuccessful in setting the row height and column widths of an excel spreadsheet from within a visual basic application.
I have a visual basic application where I have data in my clipboard. I copy that code to an instance of excel and then have excel save the resulting spreadsheet and then excel closes. I am trying to programmatically set the row heights and cell widths prior to saving the spreadsheet but have been unable to do so. This is the code that I am executing:
If SaveFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
Dim oXL As Excel.Application
Dim oWB As Excel.Workbook
Dim oSheet As Excel.Worksheet
oXL = CreateObject("Excel.Application")
oXL.Visible = True
oWB = oXL.Workbooks.Add
oSheet = oWB.ActiveSheet
oSheet.Paste()
oSheet.Cells.Select()
oSheet.Selection.RowHeight = 11.4
oSheet.Cells.EntireColumn.AutoFit()
oSheet = Nothing
oWB.Close(True, SaveFileDialog1.FileName)
oWB = Nothing
oXL.Quit()
oXL = Nothing
MsgBox("Finished!")
End If
The application runs without the oSheet.Cells.Select(), oSheet.Selection.RowHeight = 11.4, and oSheet.Cells.EntireColumn.AutoFit()
lines. With these lines, I get this error dialog message:
Public member 'Selection' on type 'Worksheet' not found.
When I trace the program in Visual Studio, the oSheet.Paste() command executes and the oSheet.Cells.Select() command executes. The exception is generated when I try to execute the oSheet.Selection.RowHeight = 11.4 command.
Any assistance would be greatly appreciated.
Jonathan
The following is not late binding, it's early binding but the pattern should work with minor code changes.
Option Strict On
Imports Excel = Microsoft.Office.Interop.Excel
Imports System.Runtime.InteropServices
Imports System.IO
Public Class Operations
Public HasError As Boolean
Public ErrorMessage As String
''' <summary>
'''
''' </summary>
''' <param name="FileName">Path and file name for Excel file</param>
''' <param name="SheetName">Sheet name to work on</param>
''' <param name="RowHeight">Used to set row height in SheetName</param>
''' <returns></returns>
Public Function SetWidthHeight(
ByVal FileName As String,
ByVal SheetName As String,
ByVal RowHeight As Integer) As Boolean
If File.Exists(FileName) Then
Dim Proceed As Boolean = False
Dim xlApp As Excel.Application = Nothing
Dim xlWorkBooks As Excel.Workbooks = Nothing
Dim xlWorkBook As Excel.Workbook = Nothing
Dim xlWorkSheet As Excel.Worksheet = Nothing
Dim xlWorkSheets As Excel.Sheets = Nothing
Dim xlCells As Excel.Range = Nothing
xlApp = New Excel.Application
xlApp.DisplayAlerts = False
xlWorkBooks = xlApp.Workbooks
xlWorkBook = xlWorkBooks.Open(FileName)
xlApp.Visible = False
xlWorkSheets = xlWorkBook.Sheets
For x As Integer = 1 To xlWorkSheets.Count
xlWorkSheet = CType(xlWorkSheets(x), Excel.Worksheet)
If xlWorkSheet.Name = SheetName Then
Proceed = True
Exit For
End If
Marshal.FinalReleaseComObject(xlWorkSheet)
xlWorkSheet = Nothing
Next
If Proceed Then
xlCells = xlWorkSheet.Cells
xlCells.PasteSpecial()
Dim EntireRow As Excel.Range = xlCells.EntireRow
'
' Set row height
'
EntireRow.RowHeight = RowHeight
Dim ColRange = xlCells.EntireColumn
'
' Auto fit all columns
'
ColRange.AutoFit()
ReleaseComObject(ColRange)
ReleaseComObject(xlCells)
ReleaseComObject(EntireRow)
Else
HasError = True
ErrorMessage = SheetName & " not found."
End If
xlWorkSheet.SaveAs(FileName)
xlWorkBook.Close()
xlApp.UserControl = True
xlApp.Quit()
ReleaseComObject(xlWorkSheets)
ReleaseComObject(xlWorkSheet)
ReleaseComObject(xlWorkBook)
ReleaseComObject(xlWorkBooks)
ReleaseComObject(xlApp)
Else
HasError = True
ErrorMessage = "'" & FileName &
"' not located. Try one of the write examples first."
End If
Return HasError
End Function
Private Sub ReleaseComObject(ByVal excelObject As Object)
Try
If excelObject IsNot Nothing Then
Marshal.ReleaseComObject(excelObject)
excelObject = Nothing
End If
Catch ex As Exception
excelObject = Nothing
End Try
End Sub
End Class
Related
I am trying to evaluate if specific cell value in an excel table is "" to use in an if statement in my VB.NET application. I modified the code that I use for writing to excel, but it doesn't work to get the cell value. The code I have:
Sub Excel_LoadProjectsSchedule()
xlApp = New Excel.Application
xlWorkBook = xlApp.Workbooks.Open("G:\100 Databases\Projects Schedule.xlsx")
xlApp.Visible = False
xlWorkSheet = xlWorkBook.Worksheets("sheet1")
Dim ProjectFinished as boolean
'Set variables
Result = xlWorkSheet.Cells.Find(ProjectNumber, LookAt:=Excel.XlLookAt.xlWhole)
If xlWorkSheet.Cells(Result.Row, 3).value = "" Then
ProjectFinished = False
Else
ProjectFinished = True
End If
'Save and close
xlApp.DisplayAlerts = False
xlWorkBook.Close(SaveChanges:=True)
xlApp.Quit()
End Sub
Error is on
If xlWorkSheet.Cells(Result.Row, 3).value = "" Then
And it says "System.MissingMemberException: 'Public member 'value' on type 'Range' not found.'
"
I do have
Public xlApp As Excel.Application = Nothing
Public xlWorkBook As Excel.Workbook = Nothing
Public xlWorkSheet As Excel.Worksheet = Nothing
Outside the sub in this module.
What am I doing wrong, could someone, please, help me solve this one?
I did some casting so the compiler can recognize the types.
Sub Excel_LoadProjectsSchedule(ProjectNumber As Integer)
Dim xlApp = New Excel.Application
Dim xlWorkBook = xlApp.Workbooks.Open("G:\100 Databases\Projects Schedule.xlsx")
xlApp.Visible = False
Dim xlWorkSheet = DirectCast(xlWorkBook.Worksheets("sheet1"), Excel.Worksheet)
Dim ProjectFinished As Boolean
'Set variables
Dim Result = xlWorkSheet.Cells.Find(ProjectNumber, LookAt:=Excel.XlLookAt.xlWhole)
Dim row = Result.Row
Dim cell = DirectCast(xlWorkSheet.Cells(row, 3), Excel.Range)
If cell.Value Is Nothing Then
'What do you want to do?
Else
If cell.Value.ToString = "" Then
ProjectFinished = False
Else
ProjectFinished = True
End If
End If
'Save and close
xlApp.DisplayAlerts = False
xlWorkBook.Close(SaveChanges:=True)
xlApp.Quit()
End Sub
I think if you specifically want to check contents in the 3rd Column of the Row with that Projectnumber you're not far away from the Solution.
I only tested it inside of VBA but something along the Lines of:
Sub Excel_LoadProjectsSchedule()
Dim xlWorksheet As Worksheet, Result As Range, ProjectFinished As Boolean
xlApp = New Excel.Application
xlWorkBook = xlApp.Workbooks.Open("G:\100 Databases\Projects Schedule.xlsx")
xlApp.Visible = False
Set xlWorkSheet = xlWorkBook.Worksheets("sheet1")
'Set variables
Set Result = xlWorksheet.Cells.Find(Projectnumber, LookIn:=Excel.XlLookin.xlValues, LookAt:=Excel.XlLookAt.xlWhole)
if not Result is nothing then
If Cells(Result.Row, 3).Value = "" Then
ProjectFinished = False
Else
ProjectFinished = True
End If
End Sub
The Problem being, that "Result" hasn't been asigned to a Range, so your code coudn't access the Row Property.
If looking for a certain cell in certain row .
Dim AppExcel As Object
Dim workBook As Object
AppExcel = CreateObject("Excel.Application")
workBook = AppExcel.Workbooks.Open("C:\SO\SO.xlsx")
AppExcel.Visible = False
Worksheets = workBook.worksheets
If Worksheets("Blad1").Cells(2, 3).text = "" Then
MessageBox.Show("Empty")
Else
MessageBox.Show("Text")
End If
Then the close part
I am trying to create an Office 365 excel spreadsheet using vb.net. I have added the following reference. Microsoft,Office 16.0 Object Library to the project.
Anything with Excel. Errors as not defined.
What's missing?
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim objApp As Excel.Application
Dim objBook As Excel._Workbook
Dim objBooks As Excel.Workbooks
Dim objSheets As Excel.Sheets
Dim objSheet As Excel._Worksheet
Dim range As Excel.Range
' Create a new instance of Excel and start a new workbook.
objApp = New Excel.Application()
objBooks = objApp.Workbooks
objBook = objBooks.Add
objSheets = objBook.Worksheets
objSheet = objSheets(1)
You have two options to resolve your issue:
Option 1: Add Imports statement:
Imports Excel = Microsoft.Office.Interop.Excel
Option 2: Specify the namespace
Dim objApp As Microsoft.Office.Interop.Excel.Application
Dim objBook As Microsoft.Office.Interop.Excel._Workbook
Try the following:
Add a Module to your project (name: HelperExcel.vb)
HelperExcel.vb
'Add Reference
'Project => Add Reference => COM => Microsoft Excel 16.0 Object Library
Imports Excel = Microsoft.Office.Interop.Excel
Module HelperExcel
Public Sub CreateExcelWorkbook(filename As String)
Dim oMissing As Object = System.Reflection.Missing.Value
Dim excelApp As Excel.Application = Nothing
Dim excelWorkbook As Excel.Workbook = Nothing
Dim excelWorksheet As Excel.Worksheet = Nothing
Try
'create New instance
excelApp = New Excel.Application()
'suppress displaying alerts (such as prompting to overwrite existing file)
excelApp.DisplayAlerts = False
'set Excel visability
excelApp.Visible = True
'disable user control while modifying the Excel Workbook
'to prevent user interference
'only necessary if Excel application Visibility property = true
'excelApp.UserControl = false
'add workbook
excelWorkbook = excelApp.Workbooks.Add()
'add a worksheet And set the value to the New worksheet
excelWorksheet = excelWorkbook.Sheets.Add()
'indices are 1-based in Excel; A1 = Cells(1,1)
'excelWorksheet.Cells(1, "A") = "Product Code"
'excelWorksheet.Cells(1, "B") = "Product Description"
excelWorksheet.Cells(1, 1) = "Product Code"
excelWorksheet.Cells(1, 2) = "Product Description"
If excelApp IsNot Nothing AndAlso excelWorkbook IsNot Nothing Then
'save Workbook - if file exists, overwrite it
excelWorkbook.SaveAs(filename, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, Excel.XlSaveAsAccessMode.xlNoChange, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value)
End If
Catch ex As Exception
Debug.WriteLine("Error (CreateExcelWorkbook): " & ex.Message)
Throw ex
Finally
If excelWorkbook IsNot Nothing Then
excelWorkbook.Close()
excelWorksheet = Nothing
excelWorkbook = Nothing
End If
If excelApp IsNot Nothing Then
excelApp.Quit()
'release all resources
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(excelApp)
End If
End Try
End Sub
End Module
Usage:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnRun.Click
'write file to Documents folder (ex: C:\Users\<username>\Documents\TestExcel.xlsx)
Dim filename As String = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "TestExcel.xlsx")
HelperExcel.CreateExcelWorkbook(filename)
End Sub
Below is my code for the copying process from one workbook to another.
I looked up a lot of similar issues but i could not get this working.
when I run this the two files open up and then i get a third one called book1 with all results. then i get an error "Copy method of Worksheet class failed".
What Im trying to do is copy the general report sheet from o.Book to xBook.
I want to leave the books open for now until this is correct but i will use Xbook later.
Can I get help with this please?
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim oExcel As Excel.ApplicationClass
Dim oBook As Excel.WorkbookClass
Dim oBooks As Excel.Workbooks
Dim xExcel As Excel.ApplicationClass
Dim xBook As Excel.WorkbookClass
Dim xBooks As Excel.Workbooks
Dim user As String
Dim opath As String
Dim opathS As String
Dim timeStamp As DateTime = DateTime.Now
Dim path2 As String
Label1.Text = "Working..."
'Get the current system user user and set path to file
user = Environment.UserName
opath = "C:\Users\" + user + "\Downloads\ADC Open.xls"
path2 = "C:\Users\" + user + "\Downloads\Personal.xlsm"
opathS = "C:\Users\" + user + "\Desktop\Report.xls"
'Create first object
oExcel = CreateObject("Excel.Application")
oExcel.DisplayAlerts = False
oExcel.Visible = True
oBooks = oExcel.Workbooks
'Create second object
xExcel = CreateObject("Excel.Application")
xExcel.DisplayAlerts = False
xExcel.Visible = True
xBooks = xExcel.Workbooks
'open first book
oBook = oBooks.Open(opath)
'open second book
xBook = xBooks.Open(path2)
oBook.Worksheets("general_report").Copy(After:=xBook.Worksheets("general_report"))
'Run the subroutine.
'xExcel.Run("Execute")
'xExcel.DisplayAlerts = False
'Delete sheet not needed any more
'xBook.Sheets("general_report").Delete
'xExcel.DisplayAlerts = False
'Save results to new file
xBook.SaveAs(opathS)
Label1.Text = "File saved at: " + opathS
'Close the workbook and quit Excel.
oBook.Close(False)
System.Runtime.InteropServices.Marshal.
ReleaseComObject(oBook)
oBook = Nothing
System.Runtime.InteropServices.Marshal.
ReleaseComObject(oBooks)
oBooks = Nothing
oExcel.Quit()
System.Runtime.InteropServices.Marshal.
ReleaseComObject(oExcel)
oExcel = Nothing
'Delete original file after finished with it
'System.IO.File.Delete(opath)
End Sub
Can't add a comment yet, but if VB is the same across all platforms, shouldn't you Set the variable after declaring it ?
Set MyObject = YourObject ' Assign object reference.
Set MyObject = Nothing ' Discontinue association.
After all the responses I started looking into these object settings and find code that help with the explainations, I refactored my previous version and this is what I came up with. It works like a charm now. Thanks everyone for the help and comments.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim xlApp As Excel.Application = New Excel.Application
Dim user As String
Dim sourcePath As String
Dim targetPath As String
Dim savePath As String
Label1.Text = "Working..."
user = Environment.UserName
sourcePath = "C:\Users\" + user + "\Desktop\Report\ADC Open (Dell GTIE JIRA).xls"
targetPath = "C:\Users\" + user + "\Desktop\Report\Personal1.xlsm"
savePath = "C:\Users\" + user + "\Desktop\Report\Report" & Format(Now(), "DD-MMM-YYYY") & ".xlsm"
Dim wbSourceBook As Excel.Workbook = xlApp.Workbooks.Open _
(sourcePath, ReadOnly:=False)
Dim wbTargetBook As Excel.Workbook = xlApp.Workbooks.Open _
(targetPath, ReadOnly:=False)
'Excel expects to receive an array of objects that
'represent the worksheets to be copied or moved.
Dim oSheetsList() As Object = {"general_report"}
wbSourceBook.Sheets(oSheetsList).Copy(Before:=wbTargetBook.Worksheets(1))
wbSourceBook.Close(True)
Hi How can I access a spreadsheet from AutoCad and take a value from there and use it on AutoCAd
Here is my code but it does not get the value , it's always empty. Don't know what's wrong
Sub move()
Dim EXCELApplication As Object
Dim ExcelWorksheet As Object
Set EXCELApplication = CreateObject("Excel.Application")
EXCELApplication.workbooks.Open AcadToExcel
EXCELApplication.Visible = True
Set ExcelWorksheet = EXCELApplication.ActiveWorkbook.Sheets("Sheet1")
modelsize = ExcelWorksheet.Cells(21, 3).Value
Size = modelsize
End Sub
I just tested this and it works just fine for me:
Public Sub GetFromExcel()
Dim sFile As String
sFile = "C:\Users\" & Environ$("Username") & "\Desktop\Test2.xlsx"
Dim EXCELApplication As Object
Dim ExcelWorksheet As Object
Dim sValue As String
Set EXCELApplication = CreateObject("Excel.Application")
EXCELApplication.workbooks.Add sFile
EXCELApplication.Visible = True
Set ExcelWorksheet = EXCELApplication.ActiveWorkbook.Sheets("Sheet1")
sValue = ExcelWorksheet.Range("A1").Value
MsgBox sValue
End Sub
If it doesnt work for you, then the problem is your filename.
I am exporting my data from visual studio data grid view into excel and I want to know how to add/save new sheets into an existing excel file.
If using OleDb the use SQL to create a sheet
Public Module Demo
Public Sub DemoOleDbCreateXls_WithHeaders()
Using cn As New OleDb.OleDbConnection With {.ConnectionString = "Your connection string"}
Using cmd As New OleDb.OleDbCommand With {.Connection = cn}
cmd.CommandText = "CREATE TABLE Members(FirstName CHAR(255),LastName CHAR(255),JoinedYear INT)"
cn.Open()
cmd.ExecuteNonQuery()
cmd.CommandText = "INSERT INTO Members (FirstName,LastName,JoinedYear) VALUES ('Kevin','Gallagher',2013)"
cmd.ExecuteNonQuery()
cmd.CommandText = "CREATE TABLE Officiers(FirstName CHAR(255),LastName CHAR(255),Rank CHAR(255))"
cmd.ExecuteNonQuery()
cmd.CommandText = "INSERT INTO Officiers (FirstName,LastName,Rank) VALUES ('Joan','Gallagher','AAA')"
cmd.ExecuteNonQuery()
cmd.CommandText = "CREATE TABLE Test1(Description CHAR(255),Amount Double)"
cmd.ExecuteNonQuery()
cmd.CommandText = "INSERT INTO Test1 (Description,Amount) VALUES ('Dues',12.99)"
cmd.ExecuteNonQuery()
End Using
End Using
End Sub
End Module
Using Excel automation
Option Strict On
Option Infer Off
Imports Excel = Microsoft.Office.Interop.Excel
Imports System.Runtime.InteropServices
Module Demo
Public Sub CreateSheetIfNeeded(ByVal FileName As String, ByVal SheetName As String)
If IO.File.Exists(FileName) Then
Dim Proceed As Boolean = False
Dim xlApp As Excel.Application = Nothing
Dim xlWorkBooks As Excel.Workbooks = Nothing
Dim xlWorkBook As Excel.Workbook = Nothing
Dim xlWorkSheet As Excel.Worksheet = Nothing
Dim xlWorkSheets As Excel.Sheets = Nothing
xlApp = New Excel.Application
xlApp.DisplayAlerts = False
xlWorkBooks = xlApp.Workbooks
xlWorkBook = xlWorkBooks.Open(FileName)
xlApp.Visible = False
xlWorkSheets = xlWorkBook.Sheets
'
' For/Next finds our sheet
'
For x As Integer = 1 To xlWorkSheets.Count
xlWorkSheet = CType(xlWorkSheets(x), Excel.Worksheet)
If xlWorkSheet.Name = SheetName Then
Proceed = True
Exit For
End If
Marshal.FinalReleaseComObject(xlWorkSheet)
xlWorkSheet = Nothing
Next
Dim workSheet As Excel.Worksheet = Nothing
Dim xlNewSheet As Excel.Worksheet = Nothing
If Proceed Then
' do work, sheet exists
Else
workSheet = CType(xlWorkSheets(1), Excel.Worksheet)
xlNewSheet = DirectCast(xlWorkSheets.Add(workSheet), Excel.Worksheet)
xlNewSheet.Name = SheetName
End If
xlWorkBook.SaveAs(FileName)
xlWorkBook.Close()
xlApp.UserControl = True
xlApp.Quit()
ReleaseExcelObject(xlNewSheet)
ReleaseExcelObject(workSheet)
ReleaseExcelObject(xlWorkSheets)
ReleaseExcelObject(xlWorkSheet)
ReleaseExcelObject(xlWorkBook)
ReleaseExcelObject(xlWorkBooks)
ReleaseExcelObject(xlApp)
Else
' file does not exists
End If
End Sub
Private Sub ReleaseExcelObject(ByVal excelObject As Object)
Try
If excelObject IsNot Nothing Then
Marshal.ReleaseComObject(excelObject)
excelObject = Nothing
End If
Catch ex As Exception
excelObject = Nothing
End Try
End Sub
End Module