I'm trying to implement a validation for the named ranges in a given workbook.
I first create a list of the named ranges when the workbook is first opened.
Then, when a macro is called, I check if all the named ranges are still in the workbook and use the property Name.ValidWorkbookParameter to check, if the named Range is still valid.
I noticed however, when I overwrite a named range (the value is then e.g. #REF) and set the named Range back to its intended value, then the property Name.ValidWorkbookParameter still returns False. Is there a way to update the Names-Collection, so the properties are shown correctly?
EDIT
Function checkNamedRanges()
Dim nm As Name
For Each nm In Names
Debug.Print nm.ValidWorkbookParameter
Next
End Function
Related
Given a certain range rngRange e.g. set rngRange = Workbooks(2).Worksheets(5).Range("C4:P49") If I use rngRange.select it will throw an error message if the table containing the range is not the active window/workbook/table (e.g. by wbWorkbook.Activate and wsWorsheet.Activate). Using rngRange.Activate by itself doesn't work (throws an error), probable a simple problem. But somehow I'm blind today.
Is it possible to "activate" the range directly without activating the workbook/worksheet first? And if not, can I get a workbook/worksheet reference from the range reference somehow (note, the whole thing is inside a function that only gets the range reference, I would like to avoid to add a wbWorkbook/worksheet reference since I have to change all function calls as well)?
rngRange.Parent 'gives you the sheet
rngRange.Parent.Parent 'gives you the workbook
So you can use them to .Activate them.
rngRange.Parent.Parent.Activate
rngRange.Parent.Activate
rngRange.Select
Alternatively as #Viktor mentioned:
Application.Goto rngRange
I have two workbooks that have a lot of the same named ranges and I need to move values from the second workbook to the first. I can do this by specifying which sheet the range is on and the name of range, but there are about 200 named ranges spread out over 20-something sheets and I only need the named ranges that are on 11 of those sheets. I could take the time to figure it out and hard code moving each one, but would really like it to be a mostly automated process. That way if a new range is added it can just be done automatically and I don't have to update the code.
The code I have so far is:
For Each Name In sheetList
Set sheet2vals = sheet2.Sheets(Name).Range(rangename)
Set sheet1vals = sheet1.Sheets(Name).Range(rangename)
sheet2vals.Copy sheet1vals
Next Name
sheetList is an array of sheet names where all the ranges are stored. That part works exactly as I need it, I just need to find a way to pull the ranges from each of the sheets and move them. However, the only way I can seem to find to get the list of named ranges is by pulling at the Workbook level, which doesn't tell me what sheet it is on.
Each Name has a RefersToRange property that gives you a Range object, and every Range has a Parent property that gives you the Worksheet it belongs to.
So if you have a Name object, you can always know what sheet it's referring to.
Sub test()
Worksheets("Sheet1").Range("A1").Value = 20
End Sub
This simple code is giving error when I compile it.
activesheet. works fine.
I want to know whats resulting in an error and how to fix it...
looks like it's not identifying the sheets, workbook etc.
The answer depends on which error you get. There can be 2 issues:
1. Workbook not specified
You have more than one workbook and Excel is looking in the wrong workbook for your sheet named "Sheet1", then you need to specify the workbook.
Workbooks("my-workbook").Worksheets("Sheet1").Range("A1").Value = 20
or if it is in the workbook where the code is running at it is better to use
ThisWorkbook.Worksheets("Sheet1").Range("A1").Value = 20
Note that you should avoid ActiveWorkbook which is not very reliable.
2. Wrong worksheet name
There is no worksheet named Sheet1. Check your worksheet names. Note that there are different ways to specify a worksheet.
Specify by number
Worksheets(1).Range("A1")
This uses the position of the worksheet in the tab bar below the worksheets. Note that is not very reliable because position can easily be changed by moving the tabs around.
Specify by tab name
Worksheets("Sheet1").Range("A1")
This is probably the most common method. The worksheet is specified by its tab name. This is more reliable than by number.
Specify by VBA name
Sheet1.Range("A1")
Here the VBA name of the sheet is used. This name can only be changed in the VB editor and is not visible to the user, and has nothing to do with the tab name. Using this ensures that the VBA code still works on the desired worksheet even if a user changes the tab name of the worksheet.
So if the tab name is Sheet1 its VBA name can be Sheet5 and it can be on position 3 in the tab bar.
Using this example …
Worksheets("Sheet1").Range("A1")
Sheet5.Range("A1")
Worksheets(3).Range("A1")
… are all 3 accessing the exact same worksheet just by different names. So better to use meaningful names (and no numbers) here to not confuse.
I have a dataset with is quite simple. When I add data at the end of it, I want to automatically get that in my chartsheet.
For example:
At this moment, the chartsheet exists with a Datasource "A1:Q10". After I enter some values within the sheet where the Datascource is, it should change to A1:R10.
But it doens't work. Here the code which ends up in
"Application or object-defined error"
Sheets("_Chartsheet-sheet").Select
Activesheet.Chartobjects(1).Activate
ActiveChart.SetSourceDate Source:=Range("A10:" & ActualLetter & "10")
As ashleedawg noted, SetSourceDate isn't a member of the Chart class - using Option Explicit and the VBE's IntelliSense & auto-complete will help prevent these. Writing it off as a typo, there's another problem with the code...
Source:=Range("A10:" & ActualLetter & "10")
Range being unqualified, if that code is written in a standard code module, it implicitly refers to whatever the ActiveSheet is - in this case...
Sheets("_Chartsheet-sheet").Select
...a chart sheet, which isn't a Worksheet and, as such, doesn't have a Range property.
An unqualified Range call, made explicit, reads as follows:
[_Global].Range("address")
The solution is to properly qualify that Range call with the Worksheet object instance you mean to work with - assuming Sheet1:
Source:=Sheet1.Range("address")
That Sheet1 is a global-scope Worksheet object that you get for free, given that your worksheet exists at compile-time. Select the worksheet under "Microsoft Excel Objects" in the VBE's Project Explorer, then look at its properties (F4): you'll notice it has a Name property with a value that corresponds to its "tab name" (the name you'd use to fetch the worksheet by name), but it also has a (Name) property, with a value that corresponds to its "code name" - that's the identifier VBA uses to generate the free global-scope object variable you can (and should) use anywhere in your code whenever you need to refer to that worksheet.
Fetching that object from the Sheets or Worksheets collection by name, puts your code at risk: unless workbook structure is protected, the user can change that "tab name" at any time, and that will break every Worksheets("name") call in your code.
If the code is written in a worksheet's code-behind, then the unqualified Range call is implicitly referring to that worksheet. In that case, explicitly qualifying Range with Me would make the code more... explicit about its intent.
Lastly, .Select and .Activate aren't needed here. Avoid Select and Activate, it's macro-recorder code that's as frail as code gets. Instead, work the object references - here I'm assuming that the code is written in the source sheet's code-behind, hence the Me qualifier in front of Range:
Dim chartSheet As Chart
Set chartSheet = ThisWorkbook.Sheets("_Chartsheet-sheet")
chartSheet.SetSourceData Source:=Me.Range("A10:" & ActualLetter & "10")
I'd like to preface this question by saying that I am an undergrad in college who knows C++ and has a very rudimentary understanding of VBA.
Now then, as stated in the title I need some help configuring some VBA code for an Excel worksheet so that whenever a cell in a column (specifically the D column) is modified it will automatically update other cells within the same row.
Essentially I want this to work such that when user Bob modifies cell D26 (for example) it will call a custom function I built and insert that code into cell B26 and then repeat with a different function for cell C26.
However, this function needs to be such that if cell D27 is modified it will only modify other cells in row 27, leaving row 26 and prior or subsequent rows alone until such a time as this function is called in D28 and so on.
I'm not entirely sure if this is even possible but I'd be gracious if anybody could help me configure this.
The code I built/scavenged from the internet for my custom function is this:
http://pastebin.com/RE0V2nrT
The second function I want to call for this project is the =TODAY() function built into Excel.
The code I have scraped together so far for checking if the cell has changed is this:
http://pastebin.com/S5E8cmty
If anybody could help me understand how to write what I'm looking for it would be much appreciated. If you have a different approach to solving the issue I would also love to hear it... as long as you could help me then enact your solution, haha!
Anyways, thanks to anybody who replies.
Have a look at the worksheet events available within the Excel namespace.
For this, you would use the Change event
If you double click on the worksheet you want to monitor, you can insert a Worksheet_Change sub. Then you can use the intersect function to check if the changed cell was within your range you want to monitor (e.g. D:D).
You can specify which cells you want to change. Here I just gave an example based on what you asked. This will put the output of your function into cell B[R] and put the current date into cell C[R]. Note that I'm using the Now() function since there is no Today() function in VBA. Since this returns both date and time, I'm using the Format function to get just the date.
Just for fun, let's go a little further into the object model and first get the Worksheet object to which the target range belongs. This is not 100% necessary - you could just rely on ActiveSheet. Now, you probably don't need to do this, and it's mostly just for fun, but it's also worth noting that if you were programmatically making changes to this sheet, but had not activated this sheet first (so another sheet was active) and you had not turned off EnableEvents you would get some strange results :)
Private Sub Worksheet_Change(ByVal Target As Range)
Dim TargetSheet As Worksheet
Set TargetSheet = Target.Parent
With TargetSheet
If Not Application.Intersect(Target, .Range("D:D")) Is Nothing Then
.Cells(Target.Row, 2) = ExtractWindowsUser()
.Cells(Target.Row, 4) = Format(Now(), "YYYY-MM-DD")
End If
End With
End Sub
Explanation
Worksheet change sub is declared like this. The Worksheet objects have pre-defined method stubs for events. Kind of like an interface, though not listed as an interface in the documentation. If you think of it in that concept, this is your event handshake. See the link I posted above for a list of the worksheet events available.
Private Sub Worksheet_Change(ByVal Target As Range)
In the next lines we are getting the worksheet object to which the object named Target belongs. You can see in the sub declaration that Target is declared as an object of the type Range. If you check out the Worksheet object (linked above) or the Range object documentation you'll see that the range object is a member of the worksheet object, and the documentation kind of sucks here, but FYI the worksheet object is contained within the Parent property. Now, originally I had my code using the ActiveSheet member of the Application object - but I've edited it for the reasons given in my answer above.
Dim TargetSheet As Worksheet
Set TargetSheet = Target.Parent
I use With Blocks to save typing the same Worksheet reference in multiple places. A With block just lets me access the members of the namespace specified (in this case members of the object TargetSheet) by typing .SomeMember. The compiler understands that every reference like this refers to whatever is specified in the opening With .... statement. I personally like this for readability, but I also recommend it for maintenance (change reference one place vs many). Also having a single reference gives a tiny, insignificant, probably not worth mentioning performance boost over multiple references as well.
With TargetSheet
Next we check whether or not Target is within the range of cells we want to watch. The If....Then should look familiar enough. For our condition we use the boolean operator Not to check if the result of the intersect function (linked above) Is Nothing. The reason we do this is to check if the return is allocated. If an object is allocated the Not SomeObject Is Nothing condition will evaluate to False. If the object is not allocated (i.e. our Intersect function failed to return anything) then the statement evaluates to True. So, from the Intersect function documentation we know that if our return is allocated, the ranges intersect and the intersecting range object was returned. Thus if we want to know if they intersect, we can just check for the opposite of a failure.
If Not Application.Intersect(Target, .Range("D:D")) Is Nothing Then
The next lines then just execute some code on cells within the same row as Target. We use the Cells member of the worksheet object to specify what cells to modify. Per the documentation, the default property for Cells is Item which lets us access a range object through a row and column index like this: .Cells[Row,Column]. So, I simply use the row of our Target object and the column you wanted (column "A" =1, "B"=2, etc. You can see this by changing excel properties to R1C1 reference style if you are interested).
.Cells(Target.Row, 2) = ExtractWindowsUser()
And I think the Format() and Now() functions are pretty well explained in the documentation.