VBA Range change selection, value doesn't change - vba

I have a range variable (called Constr) that is based on data that looks like this
Type Bound1 Bound2 Var1 Var2
X 1 2 3 4
Y 1 2 3 4
--
Z 1 2 3 4
I now use this procedure to change the selection to only the entries before the '--'
Sub Adjust_Selection(which As String, what_in As String, columns As Integer)
Dim row_nr_start As Integer
Dim row_nr_end As Integer
Dim row_nr_delta As Integer
Sheets("Main").Select
row_nr_start = Range(which).Find(what:=what_in, LookIn:=xlValues, LookAt:=xlWhole).Row
row_nr_end = Range(which).Find(what:="--", LookIn:=xlValues, LookAt:=xlWhole).Row
row_nr_delta = row_nr_end - row_nr_start
Range(which).Resize(row_nr_delta, columns).Select
This works and I can see that the selection changes, if I now call it using
Call Adjust_Selection("Constr", "Type", 5)
myitem("Constraints") = Range("Constr").Value
myitem is of type
Dim myitem As New Scripting.Dictionary
however when I access the value it still has everything in it. How can I update the value to only the first few lines up until the '--'?

You are calling Adjust_Selection with the named range Constr and afterwards refer to the named range Constraints. So, of course the result is different because you are referring to two different named ranges.
Furthermore, the named range Constr is not altered. It is merely used as a starting point and then a sub-set is Selected. But by selecting something you are not changing a named range (especially not a differently named range).
So, I am guessing that this is what you are searching for:
Call Adjust_Selection("Constr", "Type", 5)
ThisWorkbook.Names.Add Name:="Constraints", RefersTo:=Selection
myitem("Constraints") = Range("Constraints").Value
Note, that the selection of Adjust_Selection is now "saved" in the new named range Constraints and then myitem is being assigned this named range which is limited to the (correct) selection. Hence, the resulting variable (being a dictionary) contains all elements without the --.

Hi ThatQuantDude, I don't quite understand your question even after trying it out on my own. Based on the examples you gave, I assumed you want to store the selected range data into "Constraints" key? Apart from this, your sub function for selecting the range is working fine.
Call Adjust_Selection("Constr", "Type", 5)
myitem("Constraints") = Range("Constraints").Value
Appreciate if you could elaborate it further so I can better understand what you are trying to do? Thanks.

Range.Resize is a function. It will not change the range; it returns a new one. You just happen to select it, which isn't necessary. Turn your sub into a function returning the result of Range.Resize, and use this function directly on the right hand side of your assignment.
Note that you're not using the same name for your range in both lines of code, which I assume is a typo.

Related

Referencing Named Ranges in Range Function (Excel - VBA)

I'm trying to write a macro that takes a string variable as an input, with the string variable referencing a named range.
Currently what I have is:
Sub SubItems()
Dim M As String
M = "=R[-1]C"
'where M refers to row above, currently it is Manufacturers
Dim g As Range
Set g = Range(" & M & ")
ActiveCell.Value = g(2)
'For Example
End Sub
The problem is with the Set g = Range(" & M & ") syntax
I want the input argument for the Range function to be what M is, and not the literal letter M. Similar to how in C you would do printf('%s', M) for example.
Edit:
Currently how I have the excel sheet setup, is that you select a main item from a drop down menu. Then I want to select the cell below the main item and automatically fill in the rows with sub items. The sub items are stored in a named range that is named after the main item.
Hence I want my macro to automatically read the row above it (Main Item) hence why I have M = "=R[-1]C". Then I want to input that into the range function and that's the problem I'm currently facing.
I hope this clarifies my problem more clearly.
The problem is that your variable M describes a relative reference, and I do not believe you can apply a relative reference to a Range object in the manner you describe. Perhaps you want to attack your problem from a different angle? For instance:
You could use your method but rather set an absolute reference, e.g.
M = "A5"
Debug.Print Range(M).Value
Or alternatively you could specify a relative reference using code such as:
debug.print activecell.Offset(-1,0).Value
String literals are encased in double quotes, so you're essentially referencing a named Range called & M & .
If you're using a string variable, remember that its value is surrounded by quotes as well. So it should just be Range(M), or Range("=R[-1]C"), the two are the same.
Note: =R[-1]C is a very strange name, are you sure you meant this? Make sure you understand the difference between a named range and what's in the range (it looks like a formula)! Perhaps some description on what =R[-1]C is and I can help you more?
What I have understood so far - you have a named range, called M and you want to assign it to a VBA range. If this is the case, this is the code to achieve it:
Sub TestMe()
Dim g As Range
Set g = ActiveSheet.[M]
Debug.Print g.Address
End Sub

VBA: Syntax for dynamic CountIf Ranges

I'll do my best to try and explain my problem, but it's still a bit fuzzy in my mind so this might not be as clear as it should be, for which I apologize in advance.
Here's the part of my code I'm having trouble with:
If Application.WorksheetFunction.countif(Range("D:D"), Cells(x, firstcolumn).Value) _
And Application.WorksheetFunction.countif(Range("F:F"), Cells(x, firstcolumn).Value) _
And Application.WorksheetFunction.countif(Range("H:H"), Cells(x, firstcolumn).Value) Then
The idea behind this project is to check if the values in "Cells(x, firstcolumn)" are present in columns D, F and H at the same time, and then paste the values somewhere else.
However the number of columns to check for the "Cells(x, firstcolumn)" values could be changed, so values would need to be checked in any number of columns (2, 10 etc). My code works perfectly for the specified Ranges but if one is missing or more are added then it stops working.
The columns to check against are always offset by 2 from the firstcolumn and firstcolumn is always B, it will be checked against D, F, H and so on while columns C,E,G etc have other data not relevant for this part.
My best guess is to have the countif Ranges changed dynamically but I'm at a loss of when and how this should be done...
Could anyone point me towards the right direction in order to achieve this? I can post the full code if needed.
Cheers!
You need to extract a function here. Something like this:
Private Function IsPresentInRange(ByVal source As Range, ByVal value As Variant) As Boolean
IsPresentInRange = Application.WorksheetFunction.CountIf(source, value) > 0
End Function
And then you need a way to figure out what ranges you need to give it for a source parameter - that can be a function of its own, or you can hard-code them somewhere; basically you want to have a concept of a group of ranges to call that function with - this would be the simplest:
Private Function GetSourceRanges() As Collection
Dim result As New Collection
result.Add Range("D:D")
result.Add Range("F:F")
result.Add Range("H:H")
'maintain this list here
Set GetSourceRanges = result
End Function
Ideally you would have some logic coded there, so that you don't need to manually add ranges to that collection every time.
And then you can just iterate these ranges and determine if you get a count > 0 for all of them:
Dim sources As Collection
Set sources = GetSourceRanges
Dim result As Boolean
result = True
Dim sourceRange As Range
For Each sourceRange In sources
result = result And IsPresentInRange(sourceRange, Cells(x, firstcolumn).Value)
Next
If result Then
' whatever you had in that If block
End If

Creating an Excel Macro to delete rows if a column value repeats consecutively less than 3 times

The data I have can be simplified to this:
http://i.imgur.com/mn5GgrQ.png
In this example, I would like to delete the data associated with track 2, since it has only 3 frames associated with it. All data with more than 3 associated frames can stay.
The frame number does not always start from 1, as I've tried to demonstrate. The track number will always be the same number consecutively for as many frames as are tracked. I was thinking of using a function to append 1 to a variable for every consecutive value in column A, then performing a test to see if this value is equal >= 3. If so, then go onto the next integer in A, if no, then delete all rows marked with that integer (2, in this case).
Is this possible with Visual Basic in an Excel Macro, and can anyone give me some starting tips on what functions I might be able to use? Complete novice here. I haven't found anything similar for VBA, only for R.
I assume you understand the code by reading it.
Option Explicit
Public Function GetCountOfRowsForEachTrack(ByVal sourceColumn As Range) As _
Scripting.Dictionary
Dim cell As Range
Dim trackValue As String
Dim groupedData As Scripting.Dictionary
Set groupedData = New Scripting.Dictionary
For Each cell In sourceColumn
trackValue = cell.Value
If groupedData.Exists(trackValue) Then
groupedData(trackValue) = cell.Address(False, False) + "," + groupedData(trackValue)
Else
groupedData(trackValue) = cell.Address(False, False)
End If
Next
Set GetCountOfRowsForEachTrack = groupedData
End Function
Public Sub DeleteRowsWhereTrackLTE3()
Dim groupedData As Scripting.Dictionary
Set groupedData = GetCountOfRowsForEachTrack(Range("A2:A15"))
Dim cellsToBeDeleted As String
Dim item
For Each item In groupedData.Items
If UBound(Split(item, ",")) <= 2 Then
cellsToBeDeleted = item + IIf(cellsToBeDeleted <> "", "," + cellsToBeDeleted, "")
End If
Next
Range(cellsToBeDeleted).EntireRow.Delete
End Sub
GetCountOfRowsForEachTrack is a function returning a dictionary (which stores track number as key, cell address associated with that track as string)
DeleteRowsWhereTrackLTE3 is the procedure which uses GetCountOfRowsForEachTrack to get the aggregated info of Track numbers and cells associated with it. This method loops through the dictionary and checks if the number of cells associated with track is <=2 (because splitting the string returns an array which starts from 0). It builds a string of address of such cells and deletes it all at once towards the end.
Note:
Add the following code in a bas module (or a specific sheet where
you have the data).
Add reference to "Microsoft Scripting.Runtime" library. Inside VBA, click on "Tools" -> "References" menu. Tick the "Microsoft Scripting.Runtime" and click on OK.
I have used A2:A15 as an example. Please modify it as per your cell range.
The assumption is that you don't have thousands of cells to be deleted, in which case the method could fail.
Make a call to DeleteRowsWhereTrackLTE3 to remove such rows.

Macro to run through 3 conditions and provide value

This is my first time using VBA for Excel (I usually code Java and C++), and I was hoping to get some tips to start out.
I want to write a macro for a large data set that will proceed through the following list of conditions to provide a dollar result:
Collect unit size from column A (Possible values 0-8)
Determine whether single or family unit from Column B (Single- 1, Family- 0)
Collect utility code from Column C (code for type of product being assessed)
From this information, a new value will be placed in the row which determines utility costs by taking into account unit size, type of unit, and the product in question. I have thought about using nested Select Case or nested conditionals in a loop, but overall I am pretty lost.
It seems like a worksheet formula might do the trick, but it's hard to tell without knowing what the calculation is. Below is a user-defined function (UDF) that you would put in a standard module. You would call it from a cell like:
=computecosts(A2,B2,C2)
Obviously the code would change depending on how your data is laid out and what your calculation is.
Public Function ComputeCosts(rSize As Range, rFamily As Range, rCode As Range) As Double
Dim lSizeFactor As Long
Dim lFamilyFactor As Long
Dim dCodeFactor As Double
Dim rFound As Range
Const lFAMILY As Long = 0
'Size factor is a function of 0-8, namely adding 1
lSizeFactor = rSize.Value + 1
'Family factor is computed in code
If rFamily.Value = lFAMILY Then
lFamilyFactor = 3
Else
lFamilyFactor = 2
End If
'Code factor is looked up in a different sheet
Set rFound = Worksheets("Sheet2").Columns(1).Cells.Find(rCode.Value, , xlValues, xlWhole)
If Not rFound Is Nothing Then
dCodeFactor = rFound.Offset(0, 1).Value
End If
'do the math
ComputeCosts = lSizeFactor * lFamilyFactor * dCodeFactor
End Function
Thanks for the responses, they were helpful in understanding VBA for Excel. I just ended up putting possible values in a table and then using Match functions within an Index function to pick out the right value.

Problems with VLOOKUP in VBA

All,
I'm trying to use vlookup in a simple VBA function, but it is continually returning #VALUE!
Here is the code:
Public Function getAreaName(UBR As Integer) As String
Dim result As String
Dim sheet As Worksheet
Set sheet = ActiveWorkbook.Sheets("UBR Report")
' check level 3 then 2 then 4 then 5
result = Application.WorksheetFunction.VLookup(UBR, sheet.Range("UBRLookup"), Application.WorksheetFunction.Column(sheet.Range("UBRLookup[Level 3]")), False)
getAreaName = result
End Function
Any thoughts?
I'm not quite sure what you're trying to do with the "UBRLookup[Level 3]" reference, but as Joseph has pointed out, that's the bit that you're doing wrong.
[ is not a valid character for a named range in Excel.
The column that you're referencing needs to be a numeric value, the offset from the start of the table-array you've defined as your named range.
The below should work, provided the column you want to pull out is the second column in your named range (e.g. what you're referring to as [level 3] is in the second column).
Public Function getAreaName(UBR As Integer) As String
Dim result As String
Dim sheet As Worksheet
Set sheet = ActiveWorkbook.Sheets("UBR Report")
result = Application.WorksheetFunction.VLookup(UBR, sheet.Range("UBRLookup"), 2, False)
getAreaName = result
End Function
Update:
I've had a look at Excel 2007 and from what I can see the column function isn't exposed as an Application.WorksheetFunction.
You can use it on the sheet with =Column(D4), but when trying to autocomplete within the vba editor, the function isn't there. This may be due to a difference in versions, so I'll ignore that for now.
It still definitely seems like you're mis-using the third argument. If you really don't want to use the number reference we need to find out where the function is going wrong.
A few tests along the lines of
Debug.Print Application.WorksheetFunction.Column(D4)
Debug.Print sheet.Range("UBRLookup[Level 3]")
should hopefully help to show you exactly where it's going wrong - I believe that it will object to both of the above, but if it returns some useful information then we may be a step closer to your solution.
Break you function up into more pieces. Then debug it and make sure every piece is set up the way you expect.
Example:
Public Function getAreaName(UBR As Integer) As String
Dim result As String
Dim sheet As Worksheet
Set sheet = ActiveWorkbook.Sheets("UBR Report")
Dim range as Range = sheet.Range("UBRLookup")
Dim column as Column = Application.WorksheetFunction
.Column(sheet.Range("UBRLookup[Level 3]"))
result = Application.WorksheetFunction.VLookup(UBR, range, column, False)
getAreaName = result
End Function
In fact, just by doing that I noticed something weird. You use a range in two different places, but in one place you're looking for UBRLookup, and in another you're looking for UBRLookup[Level 3], is that correct?
I am disturbed by
Dim column as Column =
Application.WorksheetFunction.Column(sheet.Range("UBRLookup[Level 3]"))
You should Dim column as long, I think, and maybe use a variable name that's not to be confused with a property, like lngCol.
This part: sheet.Range("UBRLookup[Level 3]") is suspect as "UBRLookup[Level 3]" is not a valid range name.