Adding different randomly generated numbers in an Excel sheet with VB.NET - 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?

Related

Issues Preserving Format from Word to Excel

I'm struggling trying to export a Word table to an Excel sheet, while preserving the number formatting. My code works as shown below, but the part I commented out is how I'm currently trying to do it (and failing). Could someone point out what I'm doing wrong?
Public Sub CopyTableToExcel()
Dim xlApp As Excel.Application
Dim xlwb As Excel.Workbook
Dim doc As Word.Document
Dim tbl As Word.Table
Dim lastRow As Long, lastColumn As Integer
Dim tblRange As Word.Range
Dim excelRange As Excel.Range
Set doc = ThisDocument
Set xlApp = CreateObject("Excel.Application")
Set xlwb = xlApp.Workbooks.Add 'Create new workbook
Set tbl = doc.Tables(2)
With tbl:
lastRow = .Rows.Count
lastColumn = .Columns.Count
Set tblRange = .Cell(1, 1).Range
tblRange.End = .Cell(lastRow, lastColumn).Range.End
tblRange.Copy
xlwb.Worksheets(1).Paste
'This part doesn't work, but I'm trying to do something like this:
'Set excelRange = xlwb.Worksheets("Sheet1").Range("A1")
'excelRange.PasteSpecial (xlPasteValuesAndNumberFormats)
End With
Set xlwb = Nothing
Set xlApp = Nothing
Set tbl = Nothing
Set doc = Nothing
End Sub
Thanks for your help!

How do I get an Excel cell name in 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

Type mismatch error in on worksheets.range

I am making a VBA machine that takes a Word document and searches it for terms in an Excel file, then copies each sentence with the term and pastes it in the Excel sheet. I have kind of cobbled together two different pieces of code that search a Word document for a list of words from another Word document, and one that copies every sentence that uses a given word. Here is my code:
Sub thesearchmacro()
Dim excelfile As Object
Dim excelsheet As Object
Dim worddoc As Document
Dim searchcell As Range
Dim destcol As Integer
Dim destrow As Integer
Dim searchterms As Range
Dim documentrange As Range
Set documentrange = ActiveDocument.Range
Set excelfile = CreateObject("Excel.Application")
Set excelsheet = excelfile.workbooks.Open("U:\filepath\searchmachine.xlsm")
Set searchterms = excelsheet.Worksheets("Data").Range("B2:GX2")
destcol = 2
For Each searchcell In searchterms.Cells
destrow = 3
With documentrange.Find
Do
.Text = searchcell
documentrange.Expand unit:=wdSentence
documentrange.Copy
documentrange.Collapse wdCollapseEnd
excelsheet.Cells(destrow, destcol).Paste
destrow = destrow + 1
Loop While .Found
destcol = destcol + 1
End With
Next
End Sub
Whenever I run this:
Set searchterms = excelsheet.Worksheets("Data").Range("B2:GX2")
comes back with a type mismatch error.
*edit: missed a copy
added findwindow's suggestion
This is what worked in the end. If you are trying to replicate it feel free to ask me anything.
Sub thesearchmacro()
Dim excelfile As Object
Dim excelsheet As Object
Dim worddoc As Document
Dim searchcell As Object
Dim destcol As Integer
Dim destrow As Integer
Dim destcell as Object
Dim searchterms As Object
Dim documentrange As Range
Set documentrange = ActiveDocument.Range
Set excelfile = CreateObject("Excel.Application")
Set excelsheet = excelfile.workbooks.Open("U:\filepath\searchmachine.xlsm")
Set searchterms = excelsheet.Worksheets("Data").Range("B2:GX2")
destcol = 2
For Each searchcell In searchterms.Cells
destrow = 3
With documentrange.Find
Do
.Text = searchcell
.execute
If .Found Then
documentrange.Expand unit:=wdSentence
excelsheet.Sheets("Data").Cells(destrow, destcol) = documentrange
documentrange.Collapse wdCollapseEnd
destrow = destrow + 1
Loop While .Found
destcol = destcol + 1
End With
Next
End Sub
Word.Range and Excel.Range are different types.
If you are happy to add a reference to Excel to your project, do that and replace all Ranges with either Word.Range or Excel.Range as appropriate.
Otherwise declare all Excel types as Objects.

How to manipulate an excel workbook with Excel.Workbook

So, I can't find any methods with file opening in Excel.Workbook or Excel.Application, and I am wondering why.
I have path to an Excel file, and I would like to manipulate it. I understand I have to use Excel.Application, Excel.Workbook, and Excel.Worksheet. The file to the Excel file is ExcelFilePath, what should I do to make it possible?
You first need to add the reference to Microsoft.Office.Interop.Excel to your project in order to use the Excel API, then fill the variables:
Dim xlApp As Excel.Application
Dim xlWorkBook As Excel.Workbook
Dim xlWS As Excel.Worksheet
xlApp = New Excel.ApplicationClass
xlWorkBook = xlApp.Workbooks.Open(sFilePath)
xlWS = CType(xlWorkBook.Worksheets(sheetNameOrIndex), Excel.Worksheet)
And then you only need to use the methods they have. For example:
Dim sVar as String = xlWS.Range("C5").Value.ToString()
Try this: from my project
Dim xapp As New Microsoft.Office.Interop.Excel.Application
Dim wb As Workbook = xapp.Workbooks.Add
Dim ws As Worksheet = wb.Worksheets(1)
ws.Activate()
'Fill header of the sheet----------------------------------
For i As Integer = 1 To dgvcustomer.Columns.Count
ws.Cells(1, i) = dgvcustomer.Columns(i - 1).HeaderText
Next
'End header------------------------------------------------
Dim Dgrow, Dgcell, Dgcol As Integer
Dgrow = 1
Dgcell = 1
'Fill Sheet ------------------------------------------------------------------------------------------------
While (Dgrow <= dgvcustomer.Rows.Count)
Dgcol = 1
While (Dgcol <= ws.UsedRange.Columns().Count)
ws.Cells(Dgrow + 1, Dgcol).value = dgvcustomer.Rows(Dgrow - 1).Cells(ws.Cells(1, Dgcol).value).Value
Dgcol += 1
End While
Dgrow += 1
End While
'End fill sheet---------------------------------------------------------------------------------------------
wb.SaveAs(dlgSaveFile.FileName)
wb.Close()
xapp.Quit()

Getting TXT file to Excel

I have the following code to get a text file to an Excel workbook.
Dim XlApp As Excel.Application = New Excel.Application
Dim XlWbk As Excel.Workbook = XlApp.Workbooks.Add
Dim SheetName As String = "Sheet1"
Dim XlWkst As Excel.Worksheet = FindSheet(XlWbk, SheetName)
Dim XlRng As Excel.Range = Nothing
If XlWkst Is Nothing Then
XlWkst = DirectCast(XlWbk.Sheets.Add(After:=XlWbk.Sheets(XlWbk.Sheets.Count), _
Count:=1, Type:=Excel.XlSheetType.xlWorksheet), Excel.Worksheet)
End If
Dim Lines() As String = File.ReadAllLines("C:\TEMP\FlowgateNNL_Mar2011_base.txt")
Dim RC(Lines.Length - 1)() As String
For I As Integer = 0 To Lines.Length - 1
RC(I) = Lines(I).Split(CChar(vbTab))
Next
XlRng = XlWkst.Range("a1")
XlRng.Value = RC
XlApp.Visible = True
This method seems to be the fastest way to read and parse a CSV file for dumping to Excel on my computer. it is choking on XlRng.Value = RC. Excel doesn't seem to like RC.
Any ideas for getting Excel to accept the data?
You are setting the value of a cell to an array that contains an entire CSV? I'm guessing this throws a type error.
This is probably more along the lines of what you want.
Dim XlApp As Excel.Application = New Excel.Application
Dim XlWbk As Excel.Workbook = XlApp.Workbooks.Add
Dim SheetName As String = "Sheet1"
Dim XlWkst As Excel.Worksheet = FindSheet(XlWbk, SheetName)
Dim XlRng As Excel.Range = Nothing
If XlWkst Is Nothing Then
XlWkst = DirectCast(XlWbk.Sheets.Add(After:=XlWbk.Sheets(XlWbk.Sheets.Count), _
Count:=1, Type:=Excel.XlSheetType.xlWorksheet), Excel.Worksheet)
End If
Dim Lines() As String = File.ReadAllLines("C:\TEMP\FlowgateNNL_Mar2011_base.txt")
For I As Integer = 0 To Lines.Length - 1
XlRng = XlWkst.Range("a1").Offset(I, 0)
Dim RC() As String = Lines(I).Split(CChar(vbTab))
For J As Integer = 0 To RC.Length - 1
XlRng = XlRng.Offset(0, J)
XlRng.Value = RC(J)
Next
Next
XlApp.Visible = True
Did you try simply opening the CSV file directly as in:
Dim XlApp As Excel.Application = New Excel.Application
Dim XlWbk As Excel.Workbook = XlApp.Workbooks.Open("C:\TEMP\FlowgateNNL_Mar2011_base.txt")
XlApp.Visible = True
If you have a valid CSV file do yourself a favor and use a specialised CSV datareader which can handle all the weird problems of CSVs (quotes etc.)
Personally, I like http://kbcsv.codeplex.com/ very much - it is simple to use and fast.
Then just dump the interop part and use the EPPLUS Library to write the data to an excel file - it is magnitudes faster and mind boggingly simple.
Your workflow would look like this:
Use KBCSV to load the data to a datatable.
Use EPPLUS's method "LoadFromDataTable" to generate a new excel file and save it.
Done!