How do I get an Excel cell name in vb.net? - vb.net

I need the name of the first empty cell in a column, for example "E15" or "A3"
I've tried using worksheet.Cells.Name and worksheet.Rows.Name but I don't
think that is the correct syntax... please help!
Here's 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
xlApp = New Excel.Application
xlWorkBook = xlApp.Workbooks.Add(eXe)
xlWorkSheet = xlWorkBook.Sheets("sheet1")
Dim eColumn As Excel.Range = xlWorkSheet.Range("E2:E15")
Dim rCell As Excel.Range
For Each rCell In eColumn
If rCell Is Nothing Then
Dim LastCell As String = xlWorkSheet.Rows.Name
MsgBox(LastCell)
End If
MsgBox(rCell.Value)
Next rCell
(update)
I used the following code and got $E$15, is there a way to get the address with out the "$" symbol?
For Each rCell In eColumn
If rCell.Value = "" Then
Dim LastCell As String = rCell.Cells.Address
MsgBox(LastCell)
End If
MsgBox(rCell.Value)
Next rCell

To get the name of the coloumn use:
Dim columnLetter As String = ColumnIndexToColumnLetter(85) ' returns CG
Private Function ColumnIndexToColumnLetter(colIndex As Integer) As String
Dim div As Integer = colIndex
Dim colLetter As String = String.Empty
Dim modnum As Integer = 0
While div > 0
modnum = (div - 1) Mod 26
colLetter = Chr(65 + modnum) & colLetter
div = CInt((div - modnum) \ 26)
End While
Return colLetter
End Function
Thing that you already know how to get the row number you are looking for. Then just use
dim CellName as String = columnLetter & rownum ' the row number you need
This should omit any $ signs you don't want
The example is being taken from here
Regards,
Iakov

Related

Finding Last Blank Cell Of The Excel (In Column Range H8:H38), and Updating Blank Cell In Desired Range - VB.NET

Sources:
Private Sub toEditDataOnReportCell(ByVal passedData As String)
Dim monthlyReportFilePath As String = "./Report/Example.xlsx"
Dim oExcel As Object
Dim oBook As Object
Dim oSheet As Object
'Start a new workbook in Excel
oExcel = CreateObject("Excel.Application")
oBook = oExcel.Workbooks.Open(monthlyReportFilePath)
'Set which worksheet tobe modified
oSheet = oBook.Worksheets(1)
'This will find the lastRow in the sheet
'Dim lastRow As Integer = 7
Dim ETLastRow As Integer = oSheet.usedrange.rows.count
'This is next emptyRow in the sheet
Dim ETemptyRow As Integer = ETLastRow + 1
'edit last empty row val on column 8
Dim columnToMod As Integer = 8
oSheet.Cells(ETemptyRow, columnToMod).value = passedData
ETLastRow = oSheet.usedrange.rows.count
ETemptyRow = ETLastRow + 1
'This will not prompt the user to overwrite the excel sheet
oExcel.DisplayAlerts = False
oBook.Save()
oBook.Close()
oExcel.Quit()
TextBox12.AppendText("Sucess!!!" + vbCrLf + vbCrLf)
End Sub
Giving wrong last row, if in excel doc already have a table with formula in it.
Output Preview:
Targeting In Cell Range (H8:H38)
[1]: https://i.stack.imgur.com/D4RT5.png
But Output In Cell Range (H40:H)
[2]: https://i.stack.imgur.com/0wufs.png
Hehehe, i found the solutions,
Thanks to #StoriKnow & his answer there:
Here is my latest sources:
Private Sub toEditDataOnReportCell(ByVal passedData As String)
Dim monthlyReportFilePath As String = "./Report/Example.xlsx"
Dim oExcel As New Object
Dim oBook As New Object
Dim oSheet As New Object
oExcel = CreateObject("Excel.Application")
oBook = oExcel.Workbooks.Open(monthlyReportFilePath)
oSheet = oBook.Worksheets(1)
Try
Dim sourceCol As Integer, rowCount As Integer, currentRow As Integer
Dim currentRowValue As String
sourceCol = 8 'column H has a value of 8
rowCount = oSheet.Cells(oSheet.Rows.Count, sourceCol).End(Excel.XlDirection.xlUp).Row
'for every row, find the first blank cell and select it
For currentRow = 8 To rowCount
currentRowValue = oSheet.Cells(currentRow, sourceCol).Value
If (currentRowValue Is Nothing) Or (currentRowValue = "") Then
'oSheet.Cells(currentRow, sourceCol).Select
Dim preview As String = currentRow
TextBox12.AppendText(preview + " ")
oSheet.Cells(currentRow, sourceCol).Select
oSheet.Cells(currentRow, sourceCol).value = passedData
Exit Try
End If
Next
Finally
''' DO NOTHING
End Try
''This will not prompt the user to overwrite the excel sheet
oExcel.DisplayAlerts = False
oBook.Save()
oBook.Close()
oExcel.Quit()
end Sub
Output that achived:

Need to get a count of each differnt value in a column, via vb.net

I have a list of names and I need a count of how many times the name appears within the column. I am trying to use LINQ but I don't fully understand the syntax of what is happening below.
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("C:\WORK\TestFile.xlsx")
xlWorkSheet = xlWorkBook.Sheets("sheet1")
Dim AddCol As Excel.Range = xlWorkSheet.Range("b2")
Dim lastRow As Integer = AddCol.SpecialCells(Excel.XlCellType.xlCellTypeLastCell).Row
Dim Lastof As String = ("b2:" & "b" & lastRow & """").Replace("""", "")
Dim excelColumn As Excel.Range = xlWorkSheet.Range(Lastof)
'MsgBox(Lastof)
Dim Lister As New List(Of String)()
For Each Names In excelColumn
Lister.Add(Names.value)
Next
Dim Result As New List(Of String)
Result = Lister.Distinct().ToList
For Each uniqueItem In Result
Dim myList As New List(Of String) From {uniqueItem}
Dim groupedNames = myList.GroupBy(Function(x) x)
If groupedNames IsNot Nothing AndAlso groupedNames.Count > 0 Then
Dim msg As String = Nothing
For Each person In groupedNames
msg += person.Key & "-" & person.Count.ToString & vbCrLf
Next
MsgBox(msg)
End If
Next
This is what ended up working for me. I removed the "For Each uniqueItem" from my code above and it worked perfectly.
Dim groupedNames = Lister.GroupBy(Function(x) x)
If groupedNames IsNot Nothing AndAlso groupedNames.Count > 0 Then
Dim msg As String = Nothing
For Each person In groupedNames
msg += person.Key & "-" & person.Count.ToString & vbCrLf
Next
MsgBox(msg)
End If

Adding different randomly generated numbers in an Excel sheet with VB.NET

So i have an excel sheet which i am adding data to. I have made headers
Dim xlApp As Excel.Application
Dim xlWorkBook As Excel.Workbook
Dim xlWorkSheet As Excel.Worksheet
Dim xlRange As Excel.Range
Dim misValue As Object = System.Reflection.Missing.Value
Dim rNum As Random = New Random
xlApp = New Excel.Application
xlWorkBook = xlApp.Workbooks.Add(misValue)
xlWorkSheet = xlWorkBook.Sheets("sheet1")
xlRange = xlWorkSheet.UsedRange
With xlWorkSheet
.Range("A1").Value = "col1"
.Range("B1").Value = "col2"
.Range("C1").Value = "col3"
.Range("D1").Value = "col4"
.Range("E1").Value = "col5"
.Range("F1").Value = "col6"
End With
what i would like to do for col5 is have every row and individual, randomly generated number using rNum to do it. So far i have been able to populate multiple rows in the column but it is the same number and not unique
Any advice on this?
EDIT
The only code i had was this:
xlWorkSheet.Range("E2:E10").Value = rNum.Next()
You can use this code to set a different value for every cell:
For i As Integer = 2 To 10
xlWorkSheet.Range("E" & i).Value = rNum.Next()
Next i
Sincerely, Doom Guy with 100% health
Instead of using
xlWorkSheet.Range("E2:E10").Value = rNum.Next()
Try using
Dim rCell As Range
Dim rRng As Range
Set rRng = xlWorkSheet.Range("E2:E10")
For Each rCell In rRng.Cells
rCell.Value = rNum.Next()
Next rCell
Does that do the trick?

How to Import Data Into Heavy Excel File

Goal
Import about 100+ lines of data into a worksheet. Quickly.
Current Problem
The Excel file isn't very large (not even 1MB). Although, we use this Excel file to communicate with SolidEdge which makes it very heavy.
At the moment, it takes about 60 seconds to populate the 100 lines of data. Don't get me wrong, that isn't very long. Whereas I tested it with a new and empty Excel file and it took less than 1 second to populate the data.
Code
Here's my code incase I did something stupid in there:
Private Sub PopulateExcel()
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 Proceed As Boolean = False
Dim RowIndex As Integer = 2
Dim counter As Integer = 0
xlApp = CType(Marshal.GetActiveObject("Excel.Application"), Excel.Application)
xlWorkBooks = xlApp.Workbooks
For Each wb As Excel.Workbook In xlWorkBooks
If wb.Name.Contains("301-AAAA-00X") Then
xlWorkBook = wb
xlWorkSheets = xlWorkBook.Sheets
Exit For
End If
Next
If xlWorkSheets IsNot Nothing Then
For x As Integer = 1 To xlWorkSheets.Count
xlWorkSheet = CType(xlWorkSheets(x), Excel.Worksheet)
If xlWorkSheet.Name = "ImportSheet" Then
Proceed = True
Exit For
End If
Runtime.InteropServices.Marshal.FinalReleaseComObject(xlWorkSheet)
xlWorkSheet = Nothing
Next
End If
If Proceed Then
tspbProgress.Value = 0
tspbProgress.Maximum = dic_Vars.Count
tspbProgress.Visible = True
For Each key As KeyValuePair(Of String, String) In dic_Vars 'Contains all my the data
tsslStatus.Text = "Populating Excel: " & key.Key & " | " & key.Value
xlWorkSheet.Cells(RowIndex, 2).value = key.Key
xlWorkSheet.Cells(RowIndex, 3).value = key.Value
RowIndex += 1
IncProg()
Next
tspbProgress.Visible = False
ReleaseComObject(xlWorkSheets)
ReleaseComObject(xlWorkSheet)
ReleaseComObject(xlWorkBook)
ReleaseComObject(xlWorkBooks)
ReleaseComObject(xlApp)
End If
End Sub
Private Sub ReleaseComObject(ByRef obj As Object)
Try
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
obj = Nothing
Catch ex As Exception
obj = Nothing
End Try
End Sub
Conclusion
I was thinking about creating a new Excel file, importing the data there, and just doing a copy / paste to the real Excel file that we use.
Any suggestions?
Good thank you to Byron Wall who helped me find the answer. I now input my data using an array instead of iterating through each cell.
I create my array and populate it depending on how large my dictionary of variables is. I then create a new range using the Resize() method seen below.
Once that's done, everything is populated in an instant!
Dim arrNames(,) As String = New String(AscW(ChrW(dic_Vars.Count)), 1) {}
Dim arrValues(,) As String = New String(AscW(ChrW(dic_Vars.Count)), 1) {}
Dim i As Integer = 0
For Each key As KeyValuePair(Of String, String) In dic_Vars
arrNames(i, 0) = key.Key
arrValues(i, 0) = key.Value
i += 1
Next
If Proceed Then
Dim r As Microsoft.Office.Interop.Excel.Range = xlWorkSheet.Range("B2").Resize(arrNames.GetLength(0))
Dim r2 As Microsoft.Office.Interop.Excel.Range = xlWorkSheet.Range("C2").Resize(arrValues.GetLength(0))
r.Value2 = arrNames
r2.Value2 = arrValues
ReleaseComObject(xlWorkSheets)
ReleaseComObject(xlWorkSheet)
ReleaseComObject(xlWorkBook)
ReleaseComObject(xlWorkBooks)
ReleaseComObject(xlApp)
End If

How to pass sheet as an argument in Powerpoint VBA?

I have been trying to work on powerpoint that has an excel database in background.
For now I am having trouble passing sheets as arguement in PPT VBA. The function lastrow and lastcoulmn return an error that "user-defined type not defined". Help would be appreciated. thanks.
Dim oXLApp As Object
Dim oWb As Object
Dim Deps As Excel.Range
Dim Dep, Shift, Name, EmpNo, Sup As String
Dim Sups As Excel.Range
Dim Shifts As Excel.Range
Public Sub getexceldata()
Dim str As String
Set oXLApp = CreateObject("Excel.Application")
Set oWb = oXLApp.Workbooks.Open(ActivePresentation.Path & "\" & "Property Wide.xlsm")
'Shifts
Set Shifts = oWb.Sheets(4).Range("A1:A" & lastRow(oWb.Sheets(4), "a"))
'departments
Set Deps = oWb.Sheets(3).Range("A1:" & Chr(lastColumn(oWb.Sheets(3), "1") + 64) & "1")
'supervisors
End Sub
Public Function lastRow(ByVal SheetA As Excel.Application.Sheet, Optional Columnno As Char = "/") As Long
If (Columnno = "/") Then
Set lastRow = SheetA.UsedRange.Row - 1 + SheetA.UsedRange.Rows.Count
Else
Set lastRow = SheetA.Range(Columno & Rows.Count).End(xlUp).Row
End If
End Function
Public Function lastColumn(ByVal SheetA As Excel.Application.Sheet, Optional rowno As Char = "/") As Integer
If (rowno = "/") Then
Set lastColumn = SheetA.UsedRange.Column - 1 + SheetA.UsedRange.Columns.Count
Else
Set lastColumn = SheetA.Cells(rowno, Columns.Count).End(xlToLeft).Column
End If
End Function
The first issue is that CHAR is not a valid variable type so I would suggest changing this to string.
Next make sure to include the Microsoft Office Excel 14.0 Object Library in your code reference.
With that you can make some slight adjustment to your code an everything should work.
Dim oXLApp As Object
Dim oWb As Object
Dim Deps As Excel.Range
Dim Dep, Shift, Name, EmpNo, Sup As String
Dim Sups As Excel.Range
Dim Shifts As Excel.Range
Public Sub getexceldata()
Dim str As String
Set oXLApp = CreateObject("Excel.Application")
Set oWb = oXLApp.Workbooks.Open(ActivePresentation.Path & "\" & "Property Wide.xlsm")
'Shifts
Set Shifts = oWb.Sheets(4).Range("A1:A" & lastRow(oWb.Sheets(4), "a"))
'departments
Set Deps = oWb.Sheets(3).Range("A1:" & Chr(lastColumn(oWb.Sheets(3), "1") + 64) & "1")
'supervisors
End Sub
Public Function lastRow(ByVal SheetA As Worksheet, Optional Columnno As String = "/") As Long
If (Columnno = "/") Then
Set lastRow = SheetA.UsedRange.Row - 1 + SheetA.UsedRange.Rows.Count
Else
Set lastRow = SheetA.Range(Columno & Rows.Count).End(xlUp).Row
End If
End Function
Public Function lastColumn(ByVal SheetA As Worksheet, Optional rowno As String = "/") As Integer
If (rowno = "/") Then
Set lastColumn = SheetA.UsedRange.Column - 1 + SheetA.UsedRange.Columns.Count
Else
Set lastColumn = SheetA.Cells(rowno, Columns.Count).End(xlToLeft).Column
End If
End Function
With that you should have what you need.