Not Understanding why I am receiving 'Subscript Out Of Range' - vba

I have been working on this code in which I have a userform that has a mashup of listboxes and comboboxes. So far I have populated the listboxes but for some reason I am having trouble with the comboboxes (combobox1 and combobox2).
I have managed to populate the drop-down list for combobox1, and from that list I want to 'filter' through a named range that is already called out through the 'name manager'. The named range is called Range_Books.
Range_Books references two columns and a variable number of rows in table48 on sheet BOOKS or in VBA code Sheet7. The code below is my latest iteration of attempting to accomplish what I have explained but it still has failed.
I originally was attempting to call out the range directly without the Worksheets("Sheet7"). since the named range is not on a specific sheet, but I am still not sure which is the best way to call out the range and if that is the root of my problem. I have called out the range directly without the worksheets(" ") before which is why I am so perplexed by this.
It may be important to note that when the userform is initialized, it opens a secondary workbook in order to populate the listboxes. After initialization, various actions may be done before a value is chosen for combobox1, and thus activating the function I am trying to create. This secondary workbook stays open until the userform is closed. I mention this because I am unsure if the secondary workbook is causing issues with the range object. I have been receiving trouble from VBA since adding the opening of a secondary workbook functionality to the userform.
Private Sub ComboBox1_Change()
Dim count As Integer
Dim i As Integer
count = Worksheets("Sheet7").Range("Range_Books").Rows.count
For i = 0 To count
If Worksheets("Sheet7").Range("Range_Books").Cells(i, 1) = ComboBox1.Value Then
ComboBox2.AddItem (Worksheets("Sheet7").Range("Range_Books").Cells(i, 2))
End If
Next i
End Sub

You need to either start with For i = 1 to count, or change the ranges to .Cells(i+1,1)...
Also, make sure you're referring to the correct sheet. I think this is where the crux of your issue is.
If your named range is in a worksheet with the tab name "Books", then you need to instead use count = Worksheets("Books").Range("Range_Books").Rows.count
If you want to use the "Sheet7" reference instead, you could use count = Sheet7.Range("Range_Books").Rows.count

For i = 0 To count
...
Cells(i, 1)
at this point, i = 0. Row 0 Doesn't exist.
Change i = 0 to i = 1

Use this
Private Sub ComboBox1_Change()
Dim count As Integer
Dim i As Integer
Dim ws As WorkSheet
Set ws = Sheets("Sheet7")
count = ws.Range("Range_Books").Rows.count
For i = 1 To count
If Worksheets("Sheet7").Range("Range_Books").Cells(i, 1) = ComboBox1.Value Then
ComboBox2.AddItem (Worksheets("Sheet7").Range("Range_Books").Cells(i, 2))
End If
Next i
End Sub

Thank you everyone for the help, it is very much appreciated! My final working code is below. I changed all instances of Worksheets("Sheet7") to just Sheet7. I attached a picture of the Excel Objects folder tree, as you can see I have Sheet7 which I named "Books". My confusion was that Worksheets(" ") calls out the name I assign rather than the VBA assigned name for the sheet. I also added ComboBox2.Clear that way whenever ComboBox1 changes it resets the values rather then stacking them. I hope this helps somebody in the future and thanks again to the commentors who helped me!
enter image description here
Private Sub ComboBox1_Change()
ComboBox2.Clear
Dim count As Integer
Dim i As Integer
count = Sheet7.Range("Range_Books").Rows.count
For i = 1 To count
If Sheet7.Range("Range_Books").Cells(i, 1) = ComboBox1.Value Then
ComboBox2.AddItem (Sheet7.Range("Range_Books").Cells(i, 2))
End If
Next i
End Sub

Related

Exporting data from a userform output into an Excel spreadsheet

I want to ask whether anyone is familiar of a way to export data from a Userform listbox into a separate Worksheet.
For example, I have stored and displayed 3 columns ("Name", "Company" and "Position") together with multiple rows in a userform listbox and I want to transfer this into an Excel worksheet(with a click of a button) with the corresponding columns and rows.
Thanks for anyone who might provide any advice!
'Display the matching results with all parameters on new row of the results list
Rownum = ResultsList.ListCount
ResultsList.AddItem
ResultsList.List(Rownum, 0) = Name.Value
ResultsList.List(Rownum, 1) = Company.Value
ResultsList.List(Rownum, 2) = Position.Value
Else
End If
End Sub
Private Sub CommandButton1_Click()
Sheets.Add = ResultsList.Value
End Sub
I am essentially trying to get the result in "ResultsList" which is working ok, into a new sheet in excel.
Sorry for not adding in earlier.
The following seems to be what you are trying to do:
Private Sub CommandButton1_Click()
Dim m As Long, n As Long
Dim ws As Worksheet
m = ResultsList.ListCount
n = ResultsList.ColumnCount
Set ws = Sheets.Add
ws.Range(ws.Cells(1, 1), ws.Cells(m, n)).Value = ResultsList.List
End Sub
The code assumes that it is a multicolumn list and might fail with a single column (I haven't tested with that). It creates a new sheet, putting the values in the new sheet starting at A1. I'm not convinced that this is actually a good idea. I tend to find VBA code which creates new worksheets without good reason somewhat annoying -- so make sure that you have a good reason to put it on a new sheet rather than somewhere on a current sheet (perhaps at a user-selected location).

Using Vlookup to copy and paste data into a separate worksheet using VBA

Alright I'm a beginner with VBA so I need some help. Assuming this is very basic, but here are the steps I am looking at for the code:
-Use Vlookup to find the value "Rec" in column C of Sheet1, and select that row's corresponding value in column D
-Then copy that value from column D in Sheet1 and paste it into the first blank cell in column B of another worksheet titled Sheet2
I've got a basic code that uses Vlookup to find Rec as well as it's corresponding value in column D, then display a msg. The code works fine, and is the following:
Sub BasicFindGSV()
Dim movement_type_code As Variant
Dim total_gsv As Variant
movement_type_code = "Rec"
total_gsv = Application.WorksheetFunction.VLookup(movement_type_code,Sheet1.Range("C2:H25"), 2, False)
MsgBox "GSV is :$" & total_gsv
End Sub
I also have another one that will find the next blank cell in column B Sheet2, it works as well:
Sub SelectFirstBlankCell()
Dim Sheet2 As Worksheet
Set Sheet2 = ActiveSheet
For Each cell In Sheet2.Columns(2).Cells
If IsEmpty(cell) = True Then cell.Select: Exit For
Next cell
End Sub
Not sure how to integrate the two, and I'm not sure how to make the code paste the Vlookup result in Sheet2. Any help would be greatly appreciated, thanks!
So for being a beginner you're off to a good start by designing two separate subroutines that you can confirm work and then integrating. That's the basic approach that will save you headache after headache when things get more complicated. So to answer your direct question on how to integrate the two, I'd recommend doing something like this
Sub BasicFindGSV()
Dim movement_type_code As Variant
Dim total_gsv As Variant
movement_type_code = "Rec"
total_gsv = Application.WorksheetFunction.VLookup(movement_type_code, Sheet1.Range("C2:H25"), 2, False)
AssignValueToBlankCell (total_gsv)
End Sub
Sub AssignValueToBlankCell(ByVal v As Variant)
Dim Sheet2 As Worksheet
Set Sheet2 = ActiveSheet
For Each cell In Sheet2.Columns(2).Cells
If IsEmpty(cell) = True Then cell.Value2 = v
Next cell
End Sub
That being said, as Macro Man points out, you can knock out the exact same functionality your asking for with a one liner. Keeping the operational steps separate (so actually a two liner now) would look like this.
Sub FindGSV()
AssignValueToBlankCell WorksheetFunction.VLookup("Rec", Sheet1.Range("C2:H25"), 2, False)
End Sub
Sub AssignValueToBlankCell(ByVal v As Variant)
Sheet3.Range("B" & Rows.Count).End(xlUp).Offset(1, 0).Value2 = v
End Sub
Like I said, if you plan to continue development with this, it's usually a good idea to design your code with independent operations the way you already have begun to. You can build off of this by passing worksheets, ranges, columns, or other useful parameters as arguments to a predefined task or subroutine.
Also, notice that I use Value2 instead of Value. I notice you're retrieving a currency value, so there's actually a small difference between the two. Value2 gives you the more accurate number behind a currency formatted value (although probably unnecessary) and is also faster (although probably negligible in this case). Just something to be aware of though.
Also, I noticed your use of worksheet objects kind of strange, so I thought it'd help to mentioned that you can select a worksheet object by it's object name, it's name property (with sheets() or worksheets()), index number (with sheets() or worksheets()), or the "Active" prefix. It's important to note that what you're doing in your one subroutine is reassigning the reference of the Sheet2 object to your active sheet, which means it may end up being any sheet. This demonstrates the issue:
Sub SheetSelectDemo()
Dim Sheet2 As Worksheet
Set Sheet2 = Sheets(1)
MsgBox "The sheet object named Sheet2 has a name property equal to " & Worksheets(Sheet2.Name).Name & " and has an index of " & Worksheets(Sheet2.Index).Index & "."
End Sub
You can view and change the name of a sheet object, as well as it's name property (which is different) here...
The name property is what you see and change in the worksheet tab in Excel, but once again this is not the same as the object name. You can also change these things programmatically.
Try this:
Sub MacroMan()
Range("B" & Rows.Count).End(xlUp).Offset(1, 0).Value = _
WorksheetFunction.VLookup("Rec", Sheet1.Range("C2:H25"), 2, False)
End Sub
The Range("B" & Rows.Count).End(xlUp) command is the equivalent of going to the last cell in column B and pressing Ctrl + ↑
We then use .Offset(1, 0) to get the cell after this (the next blank one) and write the value of your vlookup directly into this cell.
If Both work, then good, you have two working subs and you want to integrate them. You probably want to keep them so they might be useful for some other work later. Integrating them means invoking them in some third routine.
For many reasons, it is surely better and advised to avoid as much as possible to use (select, copy, paste) in VBA, and to use rather a direct copying method (range1.copy range2).
You need to make your routines as functions that return ranges objects, then in some third routine, invoke them
Function total_gsv() as range
Dim movement_type_code As Variant: movement_type_code = "Rec"
Set total_gsv = Application.WorksheetFunction.VLookup(movement_type_code,Sheet1.Range("C2:H25"), 2, False)
End Sub
Function FindFirstBlankCell() as Range
Dim Sheet2 As Worksheet: Set Sheet2 = ActiveSheet
For Each cell In Sheet2.Columns(2).Cells
If IsEmpty(cell) Then Set FindFirstBlankCell= cell: exit For
Next cell
End Sub
Sub FindAndMoveGsv()
total_gsv.copy FindFirstBlankCell
... 'some other work
End Sub

Changing the Name of an Excel ActiveX ListBox

I have a set of ActiveX controls and subs that fit together like this:
User types into an ActiveX TextBox,
TextBox_Click triggers execution of 3 subs.
The first sub updates the value of a named range on a sheet; based on that updated value a table is created in excel using an offset function
The second sub copies the table range updated in 3 and paste.values into a range on the sheet (to eliminate formulas)
Here's where it is breaking down.
When I set the sheet up I create one ListBox (ListBox1). The third of the three subs mentioned in #2 above tests to see if ActiveX 'ListBox1' exists in the sheet. If not, the intention is the code will determine what the ListBox is called (LB1 or LB2 or LB2 etc), changes the name to 'ListBox1', and pastes the table from #4 above into ListBox1. Then a ListBox1_Click command could trigger a unique set of code to execute.
Right now I'm just testing switching between the names ListBox1 and ListBox2.
The idea is that as a user types into TextBox1 for example, ListBox1 updates at every keystroke. So type "g" and the list shows 20 names starting with the first "g" in the database sheet. Then type "ge" and the list shows 20 names starting with the first "ge" in the database sheet etc etc. The user clicks on a name and ListBox1_click does something unique. If the user was typing in TextBox2 they would see different data in the ListBox (which I would like to rename as ListBox2) and if they click a unique set of code is executed by ListBox2_Click.
The problem in #5 is the I get error 'Object doesn't support this property or method' the FIRST time I try to execute. The second time it is ok. If I do something else on the sheet and come back to it i get the error again.
Here is the code for #5 which is in a Module:
Sub PutListInListBox()
Dim OBJ As Object
On Error Resume Next
Set OBJ = ActiveSheet.OLEObjects("ListBox1")
On Error GoTo 0
If OBJ Is Nothing Then
ActiveSheet.ListBox2.Name = "ListBox1"
End If
ActiveSheet.ListBox1.Clear
ActiveSheet.ListBox1.List = Sheets("Search Criteria Control").Range("G1:G21").Value
End Sub
I have no idea what I'm doing wrong and any help is appreciated.
I hope I'm making this clear.
UPATED CODE
I have a bunch of ActiveX Lables and Text boxes so I used the first form you suggested to search for specific name Cases. I've been reading about it and can't see what I have wrong here. After typing in TB5, the LB doesn't update. I click back to Design Mode and can see that the name is still ListBox2.
Any ideas?
Private Sub TextBox5_Change()
Call UpdateValues(TextBox5.Value)
Call CopyTable
Dim OLEOBJ As OLEObject
For Each OLEOBJ In ActiveSheet.OLEObjects
Select Case OLEOBJ.Name
Case "ListBox1", "ListBox2", "ListBox3"
OLEOBJ.Name = "ListBox1"
OLEOBJ.ListFillRange = Sheets("Search Criteria Control").Range("G1:G21").Address(external:=True)
End Select
Exit For
Next
End Sub
I'll concentrate on your Code#5.
First, if you are changing the name of the ListBox Object, it is better to iterate the Object Collection it belongs to since you are not sure of it's name. Something like this:
Dim oleobj As OLEObject
Dim sh As Worksheet: Set sh = ActiveSheet
For Each oleobj In sh.OLEObjects
Select Case oleobj.Name
Case "LB1", "LB2", "ListBox1", "ListBox2" 'put the possible names here
oleobj.Name = "ListBox1" 'change it to the name you want
End Select
Exit For 'if you have more than 1 ListBox
Next
If you just want to change the name of an existing ListBox, then skip the checking.
For Each oleobj In sh.OLEObjects
oleobj.Name = "ListBox1"
Exit For 'if you have more than 1 ListBox
Next
Now, to assign values or list to it, you can directly assign the source Range, using ListFillRange Property after you've change its name.
oleobj.ListFillRange = Sheets("Search Criteria Control") _
.Range("G1:G21").Address(, , , True) 'add this line within the loop
Take note that you need not clear the previous list. It will automatically update. Since I'm not sure what you want to achieve entirely, I'll stop here. HTH though.

VBA listbox select worksheet by index

I have a form with listbox which dynamically provides a list of the worksheets in the current workbook (code below). I wish to take the selected Sheet and refer to it in a formula later in the process. From hours of playing around I cannot seem to accomplish this. I believe I read somewhere that you cannot take the string back to the sub and use it to refer to to an object. So I thought maybe I can create two listboxes
for sheet name
for sheet index
that I could pass the index number to and maybe use that in my formula to lookup items from the correct sheet.
For the life of my I cannot seem to find a way to connect the two since the items will always be changing; the code will be ran on multiple workbooks by multiple operators so the layout will most likely change between users. I can easily add the second list box with index #'s but I have a block on how to associate the name which will have meaning to the user and the index which I can pass back to the sub. I realize the "On click" procedure for the list box to associate the two but with the dynamic nature of the fields I cannot come up with the logic to put that into code.
For N = 1 To ActiveWorkbook.Sheets.Count
With ListBox1
.AddItem ActiveWorkbook.Sheets(N).Name
End With
Next N
Try this out.
Declare a public variable above the code for the UserForm, making it available throughout your workbook from any module or code.
Public listChoice As String
Using your code to get the sheet names for the ListBox rowsource.
Private Sub UserForm_Activate()
For n = 1 To ActiveWorkbook.Sheets.count
With ListBox1
.AddItem ActiveWorkbook.Sheets(n).name
End With
Next n
End Sub
Including an update event for the ListBox
Private Sub ListBox1_AfterUpdate()
listChoice = ListBox1.Text
End Sub
I included a test just to demonstrate that the result is still retained. You don't need this, it demonstrates the results on the screenshot.
Private Sub cmdTestChoice_Click()
MsgBox ("The choice made on the ListBox was: " & listChoice)
End Sub
edit: To access that sheet later, you can call it using something like this:
Some examples of different ways to access a cell, using .Range, or .Cells, with numbers or letters.
Using lRow & lCol as Long to set row and column numbers.
Sheets(listChoice).Cells(lRow, lCol).Value = TextBox1.Value 'Set cell on sheet from TextBox
TextBox2.Value = Sheets(listChoice).Range("A2").Value 'Set TextBox From Cell on Sheet
'Set a cell on another sheet using the selected sheet as a source.
Sheets("AnotherSheet").Cells(lRow, "D") = Sheets(listChoice).Range("D2")

Iterating through all the cells in Excel VBA or VSTO 2005

I need to simply go through all the cells in a Excel Spreadsheet and check the values in the cells. The cells may contain text, numbers or be blank. I am not very familiar / comfortable working with the concept of 'Range'. Therefore, any sample codes would be greatly appreciated. (I did try to google it, but the code snippets I found didn't quite do what I needed)
Thank you.
If you only need to look at the cells that are in use you can use:
sub IterateCells()
For Each Cell in ActiveSheet.UsedRange.Cells
'do some stuff
Next
End Sub
that will hit everything in the range from A1 to the last cell with data (the bottom right-most cell)
Sub CheckValues1()
Dim rwIndex As Integer
Dim colIndex As Integer
For rwIndex = 1 To 10
For colIndex = 1 To 5
If Cells(rwIndex, colIndex).Value <> 0 Then _
Cells(rwIndex, colIndex).Value = 0
Next colIndex
Next rwIndex
End Sub
Found this snippet on http://www.java2s.com/Code/VBA-Excel-Access-Word/Excel/Checksvaluesinarange10rowsby5columns.htm It seems to be quite useful as a function to illustrate the means to check values in cells in an ordered fashion.
Just imagine it as being a 2d Array of sorts and apply the same logic to loop through cells.
If you're just looking at values of cells you can store the values in an array of variant type. It seems that getting the value of an element in an array can be much faster than interacting with Excel, so you can see some difference in performance using an array of all cell values compared to repeatedly getting single cells.
Dim ValArray as Variant
ValArray = Range("A1:IV" & Rows.Count).Value
Then you can get a cell value just by checking ValArray( row , column )
You can use a For Each to iterate through all the cells in a defined range.
Public Sub IterateThroughRange()
Dim wb As Workbook
Dim ws As Worksheet
Dim rng As Range
Dim cell As Range
Set wb = Application.Workbooks(1)
Set ws = wb.Sheets(1)
Set rng = ws.Range("A1", "C3")
For Each cell In rng.Cells
cell.Value = cell.Address
Next cell
End Sub
For a VB or C# app, one way to do this is by using Office Interop. This depends on which version of Excel you're working with.
For Excel 2003, this MSDN article is a good place to start.
Understanding the Excel Object Model from a Visual Studio 2005 Developer's Perspective
You'll basically need to do the following:
Start the Excel application.
Open the Excel workbook.
Retrieve the worksheet from the workbook by name or index.
Iterate through all the Cells in the worksheet which were retrieved as a range.
Sample (untested) code excerpt below for the last step.
Excel.Range allCellsRng;
string lowerRightCell = "IV65536";
allCellsRng = ws.get_Range("A1", lowerRightCell).Cells;
foreach (Range cell in allCellsRng)
{
if (null == cell.Value2 || isBlank(cell.Value2))
{
// Do something.
}
else if (isText(cell.Value2))
{
// Do something.
}
else if (isNumeric(cell.Value2))
{
// Do something.
}
}
For Excel 2007, try this MSDN reference.
There are several methods to accomplish this, each of which has advantages and disadvantages; First and foremost, you're going to need to have an instance of a Worksheet object, Application.ActiveSheet works if you just want the one the user is looking at.
The Worksheet object has three properties that can be used to access cell data (Cells, Rows, Columns) and a method that can be used to obtain a block of cell data, (get_Range).
Ranges can be resized and such, but you may need to use the properties mentioned above to find out where the boundaries of your data are. The advantage to a Range becomes apparent when you are working with large amounts of data because VSTO add-ins are hosted outside the boundaries of the Excel application itself, so all calls to Excel have to be passed through a layer with overhead; obtaining a Range allows you to get/set all of the data you want in one call which can have huge performance benefits, but it requires you to use explicit details rather than iterating through each entry.
This MSDN forum post shows a VB.Net developer asking a question about getting the results of a Range as an array
You basically can loop over a Range
Get a sheet
myWs = (Worksheet)MyWb.Worksheets[1];
Get the Range you're interested in If you really want to check every cell use Excel's limits
The Excel 2007 "Big Grid" increases
the maximum number of rows per
worksheet from 65,536 to over 1
million, and the number of columns
from 256 (IV) to 16,384 (XFD).
from here http://msdn.microsoft.com/en-us/library/aa730921.aspx#Office2007excelPerf_BigGridIncreasedLimitsExcel
and then loop over the range
Range myBigRange = myWs.get_Range("A1", "A256");
string myValue;
foreach(Range myCell in myBigRange )
{
myValue = myCell.Value2.ToString();
}
In Excel VBA, this function will give you the content of any cell in any worksheet.
Function getCellContent(Byref ws As Worksheet, ByVal rowindex As Integer, ByVal colindex As Integer) as String
getCellContent = CStr(ws.Cells(rowindex, colindex))
End Function
So if you want to check the value of cells, just put the function in a loop, give it the reference to the worksheet you want and the row index and column index of the cell. Row index and column index both start from 1, meaning that cell A1 will be ws.Cells(1,1) and so on.
My VBA skills are a little rusty, but this is the general idea of what I'd do.
The easiest way to do this would be to iterate through a loop for every column:
public sub CellProcessing()
on error goto errHandler
dim MAX_ROW as Integer 'how many rows in the spreadsheet
dim i as Integer
dim cols as String
for i = 1 to MAX_ROW
'perform checks on the cell here
'access the cell with Range("A" & i) to get cell A1 where i = 1
next i
exitHandler:
exit sub
errHandler:
msgbox "Error " & err.Number & ": " & err.Description
resume exitHandler
end sub
it seems that the color syntax highlighting doesn't like vba, but hopefully this will help somewhat (at least give you a starting point to work from).
Brisketeer