hello guys i asked this question before but i just don't seem to find an answer can someone please tell me what i'm doing wrong in my code because even while i tried every methode on the internet no change is ever made on my excel file this my code for changing the color of a cell on an existing excel file
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim ws1 As Microsoft.Office.Interop.Excel.Worksheet
Dim xlApp As New Microsoft.Office.Interop.Excel.Application
ws1 = xlApp.Workbooks.Open(TextBox1.Text).Worksheets(ComboBox1.SelectedItem)
Dim rangeToFormat As Excel.Range
rangeToFormat = ws1.Cells(6, 5)
rangeToFormat.Interior.Color = ColorTranslator.ToOle(Color.Red)
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim xlworkbook As Excel.Workbook
Dim xlWorkSheet As Microsoft.Office.Interop.Excel.Worksheet
Dim xlApp As New Microsoft.Office.Interop.Excel.Application
OpenFileDialog1.ShowDialog()
TextBox1.Text = OpenFileDialog1.FileName
xlworkbook = xlApp.Workbooks.Open(TextBox1.Text, 0, True)
For Each xlWorkSheet In xlApp.Sheets
ComboBox1.Items.Add(xlWorkSheet.Name)
Next
End Sub
my code asks the user to choose an excel file, choose the worksheet that wants to work on and then click on a button to change the color of the cell(6,5) and other cells that i didn't add here to make my code easier to undrestand. thank you sooo much guys on advanced.
Try this:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim ws1 As Microsoft.Office.Interop.Excel.Worksheet
Dim xlApp As New Microsoft.Office.Interop.Excel.Application
ws1 = xlApp.Workbooks.Open(TextBox1.Text).Worksheets(ComboBox1.SelectedItem)
Dim rangeToFormat As Excel.Range
rangeToFormat = ws1.Cells(6, 5)
rangeToFormat.Font.Color = RGB(255, 20, 20)
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim xlworkbook As Excel.Workbook
Dim xlWorkSheet As Microsoft.Office.Interop.Excel.Worksheet
Dim xlApp As New Microsoft.Office.Interop.Excel.Application
OpenFileDialog1.ShowDialog()
TextBox1.Text = OpenFileDialog1.FileName
xlworkbook = xlApp.Workbooks.Open(TextBox1.Text, 0, True)
For Each xlWorkSheet In xlApp.Sheets
ComboBox1.Items.Add(xlWorkSheet.Name)
Next
End Sub
for the one that are still looking for the answer i actually did find it you should just add after the color command:
xlWb.Save()
xlApp.Quit()
xlApp = Nothing
Related
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
I have a datagrtidview.
I created a button "Export datagridview to Excel"
Below is the code for the export:
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
Dim xlApp As Excel.Application
Dim xlWorkBook As Excel.Workbook
Dim xlWorkSheet As Excel.Worksheet
Dim misValue As Object = System.Reflection.Missing.Value
xlApp = New Excel.Application
xlWorkBook = xlApp.Workbooks.Add(misValue)
xlWorkSheet = xlWorkBook.Sheets("Sheet1")
xlWorkSheet.SaveAs("C:\Masterlist.xlsx")
xlWorkBook.Close()
xlApp.Quit()
releaseObject(xlApp)
releaseObject(xlWorkBook)
releaseObject(xlWorkSheet)
MsgBox("You can find the file in C:\Masterlist.xlsx")
End Sub
I have also included reference: Microsoft.Office.Interop.Excel
However when I finished my project as an application, I install my application on other computer and this happens when I click on "Export to Excel" button:
https://i.stack.imgur.com/F45Q5.png
What code that can disable read-only?
Or any code here that makes this error appears?
Thanks!
hi i have a problem regarding my code in vb.net it seems this code is correct but the result is only generating the file but not the data inside the excel file i had created here is my code
Dim xlApp As Excel.Application
Dim xlWorkBook As Excel.Workbook
Dim xlWorkSheet As Excel.Worksheet
Dim misValue As Object = System.Reflection.Missing.Value
Dim i As Integer
Dim j As Integer
Try
xlApp = New Excel.Application
xlWorkBook = xlApp.Workbooks.Add()
xlWorkSheet = xlWorkBook.Sheets("Sheet1")
For i = 0 To DataGridView1.RowCount - 2
For j = 0 To DataGridView1.ColumnCount - 1
xlWorkSheet.Cells(i + 1, j + 1) = _
DataGridView1(j, i).Value.ToString()
Next
Next
xlWorkSheet.SaveAs("C:\Users\CLB Engineering Mkt\Desktop\moveoutreport.xlsx")
xlWorkBook.Close()
xlApp.Quit()
releaseObject(xlApp)
releaseObject(xlWorkBook)
releaseObject(xlWorkSheet)
MsgBox("Success")
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub releaseObject(ByVal obj As Object)
Try
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
obj = Nothing
Catch ex As Exception
obj = Nothing
Finally
GC.Collect()
End Try
End Sub
and also my datatable in gridview was like this.....
If Not con.State = ConnectionState.Open Then
con.Open()
End If
Dim da As New MySqlDataAdapter("select stock_number, item_description, quantity, unit_measure, customers_name, f_date from tbl_move_out", con)
Dim dt As New DataTable
da.Fill(dt)
DataGridView1.DataSource = dt
con.Close()
can you please help me regarding this ? Thank You in Advance
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
I'm trying to copy certain calculated values from MS excel to notepad. But its fetching empty values. can someone please check and help me resolve this issue?
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
workbook = xls.Workbooks.Open(filereader & "excelfilename.xls")
worksheet = workbook.Worksheets(1)
Dim Datawriter As New StreamWriter(filereader & "FiletoCopy.txt")
Dim range1 As Excel.Range
Dim range2 As Excel.Range
Dim range3 As Excel.Range
Dim range4 As Excel.Range
Dim range5 As Excel.Range
Dim CellValue1 As String
Dim CellValue2 As String
Dim CellValue3 As String
Dim CellValue4 As String
Dim CellValue5 As String
range1 = CType(worksheet, Excel.Worksheet).Range(“A1”)
range2 = CType(worksheet, Excel.Worksheet).Range(“A2”)
range3 = CType(worksheet, Excel.Worksheet).Range(“A3”)
range4 = CType(worksheet, Excel.Worksheet).Range(“A4”)
range5 = CType(worksheet, Excel.Worksheet).Range(“A5”)
CellValue1 = Math.Round((range1.Value), 2)
CellValue2 = Math.Round((range2.Value), 2)
CellValue3 = Math.Round((range3.Value), 2)
CellValue4 = Math.Round((range4.Value), 2)
CellValue5 = Math.Round((range5.Value), 2)
Datawriter.WriteLine(CellValue1, vbCrLf)
Datawriter.WriteLine(CellValue2, vbCrLf)
Datawriter.WriteLine(CellValue3, vbCrLf)
Datawriter.WriteLine(CellValue4, vbCrLf)
Datawriter.WriteLine(CellValue5, vbCrLf)
Datawriter.Close()
MessageBox.Show("Output Generated Sucessfully", "Success", MessageBoxButtons.OK)
End Sub
I changed the names of your worksheet and workbook. I just don't like variables named the same as the class name.
I used Path.Combine so I don't have to worry about whether the backslash is there or not.
I created and filled a list of doubles containing the values from you spreadsheet.
I am using a string builder to build the text to be saved. A StringBuilder is mutable (changeable) unlike a String. Each string would have to be discarded and a new one created otherwise.
I used the File class in System.IO to create and write the file.
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim filereader = "C:\SomeFolder\"
Dim wbook = xls.Workbooks.Open(Path.Combine(filereader, "excelfilename.xls"))
Dim wsheet As Excel.Worksheet = CType(wbook.Worksheets(1), Excel.Worksheet)
Dim lstDoubles As New List(Of Double) From {
CDbl(wsheet.Range("A1").Value),
CDbl(wsheet.Range("A2").Value),
CDbl(wsheet.Range("A3").Value),
CDbl(wsheet.Range("A4").Value),
CDbl(wsheet.Range("A5").Value)
}
'StringBuilder requires Imports System.Text
Dim sb As New StringBuilder
For Each d In lstDoubles
Dim roundedString = Math.Round(d, 2).ToString
sb.AppendLine(roundedString)
Next
File.WriteAllText(Path.Combine(filereader, "FiletoCopy.txt"), sb.ToString)
MessageBox.Show("Output Generated Sucessfully", "Success", MessageBoxButtons.OK)
End Sub
You can also try the following methods. I just slightly modified some of your code.
Imports System.IO
Imports Microsoft.Office.Interop.Excel
Public Class Form1
Dim filereader As String = "E:\Julie\Case\AccessDB\"
Dim xls As Application = New Application()
Dim Workbook As Workbook
Dim Worksheet As Worksheet
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Workbook = xls.Workbooks.Open(filereader & "exceltest.xlsx")
Worksheet = Workbook.Worksheets(1)
Dim Datawriter As New StreamWriter(filereader & "FiletoCopy.txt")
For i = 1 To 5
Dim temp As String = (CType(Worksheet.Cells(1, i), Range)).Text
Datawriter.WriteLine(temp, vbCrLf)
Next
Datawriter.Close()
MessageBox.Show("Output Generated Sucessfully", "Success", MessageBoxButtons.OK)
End Sub
End Class