range names not in name manager - vba

Running VBA code allowed me to detect that applying a filter in a sheet creates a range name that does NOT appear in the name manager (the range name either just associates to the headers or the whole table). Is there any way of knowing why this happens and/or a way of preventing it? Is it just an Excel glitch?
the part of the vba code that causes the error I tried to run was the following:
For Each Rng In ActiveWorkbook.Names
Set Rng2 = Range(Rng)
If Not Intersect(Rng2, Range(rng1.Offset(1, 0), rng1.End(xlDown)).EntireRow) Is Nothing Then ActiveWorkbook.Names(Rng.Name).Delete
Next Rng
When I was debugging, I noticed that my Rng (which is a name object, by the way) points towards a range I never created (and I know this because the sheet that it's in has no other range names and I never put any in it)
I used this vba code to verify that the name existed in this sheet:
Sub test()
Dim Rng As Name
For Each Rng In Sheets("WindHail Zone 2").Names
'ActiveWorkbook.Names(Rng.Name).Delete
MsgBox Rng
Next Rng
End Sub
I removed the comment block from the first line of the for loop to the second line to delete it. I removed the filter on that tab and reput it on, only to come to the same issue.
Thanks!

Not so clear to me what your're trying to achieve but as long as "hidden" names and range intersection are involved you must take into account what follows:
filtering does create hidden "names"
but all of them ends with the string "_FilterDatabase"
range intersection wold return an error if applied to ranges not belonging to the same sheet
so here what you should try
For Each Rng In ActiveWorkbook.Names
Set rng2 = Range(Rng)
If rng2.Parent.Name = rng1.Parent.Name And InStr(Rng.Name, "_FilterDatabase") = 0 Then 'the first check is for ranges belonging to the same worksheet and the second is for rng2 not deriving from any filtering
' now you can safely "Intersect"
If Not Intersect(rng2, Range(rng1.Offset(1, 0), rng1.End(xlDown)).EntireRow) Is Nothing Then ActiveWorkbook.Names(Rng.Name).Delete
End If
Next Rng

Related

Excel VBA Rows.Count reference for a loop

I need to pull a range of data from a sheet where the top 16 rows will always be the same but the data below will vary. I can find the starting cell with this
Sheets("AA").Next.Select
Range("A17").Select
Selection.End(xlDown).Offset(2, 2).Select
and then I want to count the cells using (starting cell selected above) to end of cells containing data. I have tried this
Range(Selection, Range(Selection.End(xlDown)).Rows.Count
and all kinds of variations on it but cannot seem to make it work. I need to be able refer back to both the start cell and the number of rows to pull data from that cell down to the last cell using a loop (another topic I will probably ask questions on when I get that far)
Can someone help?
Your explanation as to why you are trying to do this makes it appear you are placing more work on yourself than you need to.
Let's create a couple functions.
The first function we will call nextBlankCell, which will automatically grab the last cell before an empty range. In your case, we can even use your selection to determine this - which we will do in our next function.
nextBlankCell Function
Function nextBlankCell(ByVal startRng As Range) As Range
Set nextBlankCell = startRng.End(xlDown)
End Function
Next, let's create a function that will automatically set your entire range for you. In this case, it will be the range from your current selection to the last row containing data that we get from using the above function.
getRngDownwards Function
Function getRngDownwards() As Range
Dim celStart As Range, celEnd As Range, ws As Worksheet
Set celStart = Selection
Set ws = celStart.Parent
Set celEnd = nextBlankCell(celStart)
Set getRngDownwards = ws.Range(celStart, celEnd)
End Function
In the above function, we have two ranges celStart and celEnd. celStart is simply your current selection. I always prefer to immediately set your selection to a static range if you must use Selection (most cases it’s not necessary).
celEnd is the range that will contain the last used cell in your column.
We also determine the worksheet ws by using the selection's parent object. Protip: We avoided ActiveSheet!
Now you can put it to the test:
Sub test()
' This test shows you the address of the range
MsgBox getRngDownwards.Address
' This test visually shows you the range
getRngDownwards.Select
End Sub

Create a range using named cells

I need to create a range using named cells in vba.
So far I have the following which is not working;
Dim pasteRange As Range
Set pasteRange = Range(firstRow, 11)
pasteRange.Value(11) = slabTemplateSheet.Range("slabTemp").Value(11)
Where firstRow is an Integer. slabTemplateSheet refers to a worksheet and slabTemp is a named range in said sheet.
I thought it would be fairly simple as my paste range is only 1 row and 11 columns (i.e 11 cells in a row) but I can't get it to work.
In your answer, presuming there is one, could you also please give me the ability to paste multiple rows and columns, so for instance if slabTemp refers to A1:F16
Edit: I didn't make it clear what I am trying to do.
I have a named range called slabTemp in the worksheet slabTemplateSheet. In another sheet I want to copy that range, including the formatting, and paste it. I heard that using the copy/paste function was slow so I found the property above that supposedly does the same thing but is faster (i haven't tested it). Source, Durgesh's answer here: fast way to copy formatting in excel
In the new sheet I need to paste it into a range which is to be created (this is what i don't know how to do)
So Range(firstRow, 11) refers to the integer saved as firstRow (a row number) and 11 is the column number. But this doesn't work.
I guess my question, is how do i create a range using names rather than say Range("A1:G6") so instead Range(firstRow1:secondRow:6)
Thanks Again!
Here's a working example.
Public Sub CopyRange()
'Define the Copy Range
Dim CopyRange As Range: Set CopyRange = Range("MyCustomRange")
'Define the range to Paste Value to
Dim PasteRange As Range: Set PasteRange = Range("MyOtherCustomRange")
'Move the Copy Range into the Paste Range
'You don't need to specify the sheet name, the Defined named holds that information
'Important: The ranges should be the same size, otherwise you may get an error
PasteRange.Value() = CopyRange.Value()
End Sub
About how to create a Named Range (worksheet scope, not for Workbook per your code), use the code below. Not sure what are you trying to achieve in this line:
pasteRange.Value(11) = slabTemplateSheet.Range("slabTemp").Value(11)
Anyway, this is the code for the Named Range:
Sub UseNamedRange()
Dim slabTemplateSheet As Worksheet
Dim pasteRange As Range
Set slabTemplateSheet = Sheets("Sheet1")
' create the Named Range "slabTemp" (Named Range for Worksheet)
' you can manualy (or with variables) modify the Range("A1:F16")
slabTemplateSheet.Names.Add "slabTemp", Sheets("Sheet1").Range("A1:F16")
Set pasteRange = slabTemplateSheet.Range("slabTemp")
End Sub
It doesn't seem like you are trying to transfer the xlRangeValueXMLSpreadsheet XlRangeValueDataType enumeration of the cells; rather it sounds like you want 11 cells in a row.
with slabTemplateSheet.Range("slabTemp")
pasteRange.Resize(1, 11) = .Cells.Resize(1, 11).Value
end with

Copy and paste data from dynamic table while exluding formula blanks

I'm trying to copy only data (excluding blanks created by If statement) from "Data" tab then paste to the bottom of a data column on the "Summary" tab. The trouble arises from trying to figure out how to get VBA to recognize the range of usable data.
There are a couple of different ways to do this, depending on what you need. Here's one SO thread that discusses a few uses. Here's another page that discusses using UsedRange or .Rows. And, as #findwindow noted, you can use .xlEnd.
This is a pretty common use of VBA, so if you Google around (or even look through SO), you'll find some information.
Edit: Per your comment, just set a range, and loop through the cells in the range until you find a non-numeric number:
Dim rng as Range, cel as Range
Dim lastRow as Integer
Set rng = Range("A1:A10000")
for each cel in rng
If not isnumeric(cel.value) then
'Do whatever code you want, when the cell is NOT numeric, ie
lastRow = cel.Row
End if
next cel

Copy the contents and formatting of a cell if a column within the row = today()

I'm currently building a small project planner in Excel that uses the current date to plot coloured blocks under a date column to depict which stage of the project we are currently at for a particular customer (see image below).
Behind each of the coloured blocks is a drop-down menu populated by a list on another sheet. My aim is to search for the current date in cell A1 ( populated using today() ) within all columns that follow the freezed panes (depicted by the black right hand border). When the current date is found, the value of in each of the coloured blocks should be copied into the corresponding cells so that as the project progresses, a line of coloured blocks are entered for each day (with the relevant text from the drop-down depicting the current stage of that block).
Currently I am using the following formula copied into all cells that follow the freeze:
=IF(F$1 = $A$1,$C2,"")
However, when the current date is changed this merely moves the copied blocks across to the relevant column without maintaining the old values from previous days.
I've also attempted this with a VLOOKUP so that I can enter it into a macro and run if from a button but the layout does not allow for a successful VLOOKUP.
The simplest solution I believe would be to have a button that allows the user to save the current state of the column with a header that matches the current date however it has been some time since I have coded in VBA and do not remember how to do this.
Any ideas? Thanks in advance.
Not sure if this is exactly what you're looking for, but here goes...
Sub ColorCode()
Dim ws As Worksheet
Dim rng As Range
Dim cel As Range
Set ws = ThisWorkbook.Sheets("SheetNameHere")
Set rng = ws.Range("F1:I1")***
For Each cel In rng
If cel.Value = ws.Range("A1").Value Then
ws.Range("C2:C8").Copy
ws.Range(Cells(2, cel.Column), Cells(8, cel.Column)).PasteSpecial Paste:=xlPasteValues
ws.Range(Cells(2, cel.Column), Cells(8, cel.Column)).PasteSpecial Paste:=xlPasteFormats
End If
Next
End Sub
If you add that to a new module, you can assign it to a command button. I haven't had a chance to test it, but it cycles through the dates in the first row to see if they match the date in A1. If they do, it copies over the values and formats from C2:C8(change if you need to) into the rows underneath that date. You may need to change some of the ranges to suit your specific worksheet.
So your requirements seem fairly straightforward to me:
you need the tracker to identify the column with today's date
you need to establish a permanent value for each day as it occurs
you need the color of today's values to be added to the cell, and stay that way even after today's date has passed.
The formula you cite in your question, if copied across all cells, will clearly just provide a value on the column for today's date, and unless you use a circular reference to let it self assess and update its value on today's date, it will not retain information when tomorrow comes.
Your idea for a button would work if you want the user to control the time of update, or you could have code that runs either when the workbook opens or when the worksheet itself is activated (placing it in the appropriate object code under either Private Sub Worksheet_Activate() or Private Sub Workbook_Activate().
I think PermaNoob has a right idea of copying the value of the column and pasting the value (rather than the formlula) into that column, but what is missing is appropriate identification of the column containing today's date and the coloring of those cells (if you don't have some method of coloring them that you did not mention). Something like this might work either attached to a button as you suggest, or to the _Activate event as I suggest. This is untested but should give you an idea of how to approach it:
Sub UpdatePlanner()
'~~>dim variables and set initial values
Dim wb As Workbook
Set wb = Workbooks("NAME or INDEX of YOUR workbook")
Dim ws As Worksheet
Set ws = wb.Worksheets("NAME or INDEX of YOUR sheet")
Dim rngHeader As Range
Set rngHeader = ws.Range("F1", ws.Range("F1").End(xlToRight))
Dim rngDate As Range
Dim rngColumn As Range
Dim rngCell As Range
'~~>loop to find the column with today's date
For Each rngDate In rngHeader
If rngDate.value = ws.Range("A1").value Then
Set rngColumn = ws.Range(rngDate.Address, _
ws.Range(rngDate.Address).Offset(65536, 0).End(xlUp)) 'this assumes
'your column may not have a value in every row
Exit For
End If
Next rngDate
'~~>copy and paste the column values and formats
With rngColumn
.Copy
.PasteSpecial Paste:=xlPasteValues
.PasteSpecial Paste:=xlPasteFormats
End With
'~~>loop to add the color formatting (since I don't see this in your formula)
For Each rngCell In rngColumn
If rngCell.value = ws.Range(Cells(rngCell.Row, 3)).value Then
rngCell.Interior.Color = _
ws.Range(Cells(rngCell.Row, 3)).Interior.Color
End If
Next rngCell
End Sub

Referring to Dynamic Named Ranges in VBA

I'm having troubling referring to a Dynamic Name Range in VBA.
My ranges are defined as
=OFFSET(Sheet!$B$2,0,0,COUNTA(Sheet!$B:$B)-1,1)
My code should search one range for all entries in another range, the intention being that any missing entries will be added. So far I have
Sub UpdateSummary()
Dim Cell As Range
Dim rngF As Range
Set rngF = Nothing
' Step through each cell in data range
For Each Cell In Worksheets("Aspect").Range("A_Date")
' search Summary range for current cell value
Set rngF = Worksheets("Summary").Range("Sum_Date").Find(Cell.Value) // Does not work
If rngF Is Nothing Then
' Add date to Summary
End If
Set rngF = Nothing
Next Cell
End Sub
The For loop seems to work ok. However, using the .Find method is giving me an error message.
Application-defined or object-defined error
It does work if I replace the named range with a specific range ($B$2:$B$5000), so it seems to be down to how the named range is being passed.
Any ideas would be appreciated.
Thanks.
The error is almost definitely because Excel can't find a named range Sum_Date that refers to a range on a worksheet named Summary. The most common causes are
Sum_Date refers to a sheet other than Summary. Check the RefersTo property of Sum_Date and make sure nothing is misspelled.
There is not a named range Sum_Date, that is, it's misspelled in the VBA code. Check the spelling of the named range in the Name Manager.
There is an error in the RefersTo formula of Sum_Date. It sounds like you already verified that this isn't the case.
I've had the a similar if not the same problem & here's how I solved it:
I first realized that the method I used to create my named range, using the Name Manager, my named range had a scope of Workbook. This is important because, it doesn't belong to the worksheet, & therefore will not be found there.
So, Worksheets("Summary").Range("Sum_Date") would not work for me.
Since my range belonged to the workbook, the way I was able to find is to use ActiveWorkbook.Names("Sum_Date")
For me I used it to remove the formula from named range that I am using in many places. The huge advantage is that named range is updated only once instead of the formula being called for every cell location that ranged is called. Huge time delay difference!
Public last_Selection As String
Private Sub Worksheet_Change(ByVal Target As Range)
'excel data change detection
If Range(last_Selection).Column = 2 Then
'Disable events, so this only executes once
Application.EnableEvents = False
'This can be done with a complex formula in a cell,
'but this is easily understood
Range("B1").End(xlDown).Select
ActiveWorkbook.Names("last_Entry").Value = ActiveCell.Row
'Re-enable so this routine will execute on the next change
Application.EnableEvents = True
End If
End Sub
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
'constantly store the last cell to know which one was previously edited
last_Selection = Target.Address
End Sub
I know this is a very old thread, but I had the same issue today and I was looking for solution for quite a long time. So maybe this will help someone.
The named "range" defined by the =OFFSET(...) formula is actually a named FORMULA, so in VBA you have to evaluate it first to get the range. E.g.:
Set rgNamedRange = Worksheets("Summary").Evaluate("Sum_Date")
Credits to a guy named "shg" from mrexcel.com, who got me on right track. :)
I have been experimenting with this for a few days and eventually I came up with the following. It may not be the most efficient but it did work for me!
The named range of "OhDear" was set up in the normal way
Dim vItem As Variant
Set vItem = Names("OhDear")
Debug.Print vItem.Name
Worth a try don't you think!
This does not work if instead of using a variant you use something like: Dim Nm as Name: Set Nm = Names("OhDear"). Any variations using 'Nm' failed!!!