Dim n variables where n is a user defined number - vb.net

I have to dim n variables in my software, where n is a number that user types in the interface. I'd start with a for loop, in order to declare these variables, with something like:
for i = 0 to n
dim r.i as IRow = worksheet.CreateRow(i)
next
This is what I think but obviously I know that's wrong. Does anyone knows if this is possible? I can't create neither List(Of) nor arrays because these are rows of an excel file I'm trying to export, otherwise NPOI returns me error.

What does Excel have anything to do with not using a List? You can absolutely use worksheet.CreateRow() with a list:
Dim rows As New List(Of IRow)
For i As Integer = 0 to n - 1
rows.Add(worksheet.CreateRow(i))
Next
Now the name of each row is row(0), row(1), row(2) ... row(n - 1)
If you've tried this and NPOI is giving you an error, you should show that code around where the error is thrown and tell us what the error is.
Based on comments:
'Assuming everything has the same number of entries as ListBox1, per the comments
Dim rows As New List(Of IRow)
Dim row As IRow = worksheet.CreateRow(0)
row.CreateCell(0).SetCellValue("Time")
row.CreateCell(1).SetCellValue("hrr")
For i As Integer = 0 To ListBox1.Items.Count - 1
row = worksheet.CreateRow(i+1)
row.CreateCell(0).SetCellValue(ListBox1.Items(i))
row.CreateCell(1).SetCellValue(ListBox2.Items(i))
rows.Add(row)
Next i

Related

Different sections in a table (multiple empty rows). Create a conditional loop that inputs an empty row to the correct section - VBA

I have an issue I'm unable to resolve myself and was wondering if anyone here could help me. I have table with a lot of values which are broken down into different sections (separated by an empty row). I need to be able to control where a new row is inserted with the use of a macro.
What I would like to do is to create a macro with conditions so that I can control where an empty row are to be inserted. My take is to create separate buttons next to each sections (before an empty row) that assigns a value so that loop may skip through x number of empty rows before inserting a new row. My first take is like this:
Sub InsertNewRow()
Dim erow As Integer
Dim number As Integer 'number of empty rows to skip
Dim count As Integer 'to keep track on number of empty rows to skip
Dim LastRow As Long
erow = ActivityInput.UsedRange.Rows.count
count = 0
For Each l In erow
Do While i <> ""
Next erow
count = count + 1
If element = count Then
'Cells(Rows.count, 1).End(xlUp).Offset(1, 0).EntireRow.Insert
'This is as far as I got. I don't know how to make the macro go to the last row of the current section... any suggestions?
..
To clarify, I would like to add macro(s) (bottons) that helps the user to insert new rows. If the user is at section 3 (2 empty rows have been passed which separates the different sections), I would like the user to be able to click on the macro (button) which then subsequently adds a new row to the current section.
Any ideas?:/
Regards,
Alexander
Sub InsertNewRow(X As Integer)
Dim count As Integer
count = 0
For i = 1 To ActivityInput.Range("X[ABC]")(i)
If i <> "" Then Next i
ElseIf X = count Then
Cells(l, 1).End(xlDown).Offset(1, 0).EntireRow.Insert
Else
count = count + 1
Next l
End Sub

Visual Basic- Random Numbers

I'm trying to generate 5 random numbers from 1-99 and display them in a ListBox. Can someone tell me where I'm going wrong? Right now my code is displaying all 99 numbers in the ListBox, but I only want 5 of them to display. Here is the code:
'list to store numbers
Dim numbers As New List(Of Integer)
'add desired numbers to list
For count As Integer = 1 To 99
numbers.Add(count)
Next
Dim Rnd As New Random
Dim SB As New System.Text.StringBuilder
Dim Temp As Integer
'select a random number from the list, add to listbox and remove it so it can't be selected again
For count As Integer = 0 To numbers.Count - 1
Temp = Rnd.Next(0, numbers.Count)
SB.Append(numbers(Temp) & " ")
ListBox2.Items.Add(numbers(Temp))
numbers.RemoveAt(Temp)
Next
Replace
For count As Integer = 0 To numbers.Count - 1
With
For count As Integer = 1 To 5
The above will work but, You need to add count just after your next statement as well. I recommend checking into learning more about loops as well. Clearly Visual Basic 2012 is great for that.

Iterating over a collection (VBA)

Hello I am new to VBA and I am trying to iterate over a collection i've made and execute an action for each value.
Here is my code:
Sub makeRowsMatch()
Dim rows As VBA.Collection
Set rows = New VBA.Collection
Dim i As Integer
Dim j As Integer
Dim y As Integer
For i = 2 To 22203
For j = 2 To 121
If Cells(i, 2).Value <> Cells(j, 38) Then
rows.Add (i)
End If
Next j
Next i
For Each y As Object in rows
rows(y).Delete
Next y
End Sub
I keep on getting an error in the line:
For Each y As Object in rows
It keeps on getting highlighted yellow, but when I remove the above line is get the following error:
For Each control variable must be Variant or Object
Could someone explain why it is not letting me iterate over the values?
The whole issue of declaring variables is new to me.
Thanks!
Declare y as Variant, i.e.:
Dim y As Variant
and change your loop like this:
For Each y In rows
Then the loop will work or, at least, it won't give you an error at that point.
But the next problem/error is inside the loop. This line:
rows(y).Delete
will give you an error "Object required", or something like that, because rows(y) return an Integer, so you can't call Delete on it. There's some confusion here because rows on its own means the Rows range of the active sheet. But you also named your collection as rows, so there's a naming conflict.
Rename your rows to, for example, myrows and it should then all work. However, I don't know what you're trying to do with the Delete line, so I can't advise further.
You've got a conflict in your declarations and use. This line declares y as an Integer, clearly:
Dim y As Integer
But you then try to use it as an Object, either with
For Each y As Object in rows
or
For Each y in rows
Change the declaration to
Dim y As Object
(I'm not that familiar with VBA. If the above doesn't work, change the declaration to Dim y As Variant instead.)

Is it possible to add cases to a Select Case based on the number of entries in a table?

I've been messing around with VBA in Excel a bit recently; and as a small project for myself, I'm trying to create a "draw names from a hat" sort of macro.
I began by generating a random number, and then choosing which entry from a Table (i.e. ListObject) would be selected using a case statement. The problem with this is that it only works of the number of Table entries is always the same.
So my question (probably a ridiculous one) is: is it possible at all to generate a dynamic 'Select Case' block, where the number of cases on the block is based on the number of entries in the Table?
Thanks.
-Sean
Edit: To clarify: what I am trying to do, exactly, is this:
I generate a random number, i, from 1 to n=10*(number of Table entries). After this, I want to display, in a cell, one of the table entries based on the random number.
Ideally, the code would work similarly to this:
if i = 1 to 10 then choose event 1
if i = 11 to 20 then choose event 2
if i = 21 to 30 then choose event 3
...
if i = (n-9) to n then choose event (n/10)
I hope this helps to clarify the goal of the code.
From our comments here is something you can use:
Sub random()
Dim used_rows As Integer
Dim random As Integer
Dim cell_array() As Integer
used_rows = Sheet1.UsedRange.Rows.Count
ReDim cell_array(used_rows)
For i = 1 To used_rows
cell_array(i - 1) = Cells(i, 1)
Next
random = Int(Rnd * (used_rows))
MsgBox cell_array(random)
End Sub
You can go ahead and change MsgBox to whatever you like, or set like Cell(1,4).Value = cell_array(random), or however you'd like to proceed. It will be based off the number of rows used. Though depending on how you implement your spreadsheet the code might have to be changed a bit.
Here's the update code from the suggestions from the comments. Also remember to use Randomize() in your form initialization or WorkBook Open functions.
Sub random()
Dim used_rows As Integer
Dim random As Integer
'Multiple ways to get the row count, this is just a simple one which will work for most implementations
used_rows = Sheet1.UsedRange.Rows.Count
random = Int(Rnd * (used_rows))
'I use the variable only for the reason that you might want to reference it later
MsgBox Cells(random, 1)
End Sub
This assumes that by "table" you mean "Table with a capital T", known in VBA as a ListObject:
Sub PickRandomTens()
Dim lo As Excel.ListObject
Dim ListRowsCount As Long
Dim RandomNumber As Long
Dim ListEvent As String
Dim Tens As Long
Set lo = ActiveSheet.ListObjects(1)
ListRowsCount = lo.DataBodyRange.Rows.Count
RandomNumber = Application.WorksheetFunction.RandBetween(10, ListRowsCount * 10)
ListEvent = lo.ListColumns("Data Column").DataBodyRange.Cells(Int(RandomNumber / 10))
MsgBox "Random number: " & RandomNumber & vbCrLf & _
"Event: " & ListEvent
End Sub

excel vba moving non-contiguous range selection to an array

In the situation where the user select two non-contiguous column ranges i wrote the following:
Dim count long
Dim points variant
Dim i long
Set user_range = ActiveWindow.RangeSelection
count = user_range.count / 2
ReDim points(1 To count, 1 To 2)
For i = 1 To count
MsgBox "value is" & user_range.Areas.Item(1).Value(i,1)
points(i, 1) = user_range.Areas.Item(1).Value(i,1)
points(i, 2) = user_range.Areas.Item(2).Value(i,1)
Next i
But i get an object error when i try this. Am i indexing Value wrong?
This should work right? Is there an easier way to do this?
Any help is greatly appreciated!
Thanks,
Russ
I'm afraid your code does not compile. First of all, you need to declare your variables correctly. You should also use Option Explicit.
Option Explicit
Dim count As Long
Dim points As Variant
Dim i As Long
Dim user_range As Range
The count and ReDim lines are OK, but you are assuming that the two selections are both the same size. Will that always be the case?
Then I'm not sure what it is you want to do, but I'm guessing you just want to save the values in user_range into points.
You need to adress them a bit different:
points(i, 1) = user_range.Areas(1).Cells(i, 1).Value 'Selection 1
points(i, 2) = user_range.Areas(2).Cells(i, 1).Value 'Selection 2