Hello,
The following code I seeded a cell with "ABC...DEF" where the dot is a space, so that cell value has a length of 9 and upon running the code got the proper cell value with embedded spaces. Please note that the code was done in VS2010 but should work in VS2005.
Special notes: There is a good deal of code to read several cells, this is done to ensure all objects used to access Excel are properly disposed.
Code:
Public Class Form1
Private Sub cmdGetCells_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdGetCells.Click
' Open a file named File1.xlsx, read from sheet named 'Sample'
' get values for cells from string array.
Dim FileName As String = IO.Path.Combine(Application.StartupPath, "File1.xlsx")
Dim Cells = GetSomeCells(FileName, "Sample", New String() {"F11", "E10", "F10", "I10", "I11", "M4", "O4"})
Dim sb As New System.Text.StringBuilder
sb.AppendLine("Cell values from array")
For Each cell In Cells
Console.WriteLine("{0}={1} {2}", cell.Key, cell.Value, cell.Value.Length)
sb.AppendLine(String.Format("{0}={1}", cell.Key, cell.Value))
Next
sb.AppendLine("Value for F10")
sb.AppendLine(Cells("F10"))
MessageBox.Show(sb.ToString)
End Sub
End Class
Code module
Code:
Option Strict On
'Option Infer On
Imports Excel = Microsoft.Office.Interop.Excel
Imports Microsoft.Office
Imports System.Runtime.InteropServices
Module ExcelOperations
Public Function GetSomeCells(ByVal FileName As String, ByVal SheetName As String, ByVal Cells As String()) As Dictionary(Of String, String)
Dim Dict As New Dictionary(Of String, 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
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
Runtime.InteropServices.Marshal.FinalReleaseComObject(xlWorkSheet)
xlWorkSheet = Nothing
Next
If Proceed Then
For Each cell In Cells
xlCells = xlWorkSheet.Range(cell)
Dict.Add(cell, CStr(xlCells.Value))
ReleaseComObject(xlCells)
Next
End If
xlWorkBook.Close()
xlApp.UserControl = True
xlApp.Quit()
ReleaseComObject(xlCells)
ReleaseComObject(xlWorkSheets)
ReleaseComObject(xlWorkSheet)
ReleaseComObject(xlWorkBook)
ReleaseComObject(xlWorkBooks)
ReleaseComObject(xlApp)
End If
Return Dict
End Function
Public Sub ReleaseComObject(ByVal obj As Object)
Try
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
obj = Nothing
Catch ex As Exception
obj = Nothing
End Try
End Sub
End Module
Attachment 99631