简体   繁体   中英

Calling a custom built VBA function when an Excel cell is changed

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 (eg 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 (ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM