简体   繁体   中英

Upon cell value change, move to another cell & execute formula in that cell

I have a dropdown in i7. In j7 I have a formula, that adjusts the hyperlink -- based on value in i7. HLinks are to different cells in the same worksheet. Trying to get XL to automatically jump to j7 upon value change in i7, and to follow/execute the corresponding HLink, meaning for the j7 to act as if it was clicked on (but without the use of sendkeys-left mouse click). So far either line of below code, executed one at a time - on j7, gives "Run-time error '9': Subscript out of range"

Sub HLink_follow()

ActiveCell.Hyperlinks(1).Follow
ActiveWorkbook.FollowHyperlink ActiveCell.Hyperlinks(1).Address

End Sub

Am aware that this all can be done via VBA, without even having j7, but want to keep it the way that it is. If you are not clear on something, ask a question.

When you use the Hyperlink -function in a formula, it doesn't add an entry to the hyperlink-collection of a cell. With other words, ActiveCell.Hyperlinks.Count is 0 and ActiveCell.Hyperlinks(1) therefore gives an Subscript out of range.

There is a question here on SO about that, have a look to this answer: https://stackoverflow.com/a/40343924/7599798 . It suggests to parse the formula (split it by quote character) to get the URL and use FollowHyperlink with the extracted URL.

Now your case is more complicated as your cell doesn't contain only a simple =Hyperlink(..) -formula and therefore parsing is not an option. I see 2 possible solutions:

a) Instead of using a formula, add the Hyperlink via the Link-menu in Excel or the Worksheet.Hyperlink.Add method. Then add the logic to change the address in the Change-Trigger of your worksheet whenever some relevant data is changed.

b) Use a helper cell to calculate the destination of the hyperlink. The helper cell (let's say H7) would get a formula like IF(COUNTIF(I7,"x1"),"#A591",IF(COUNTIF(I7,"x2"),"#A665")). Your HLink_follow-routine would use the calculated address of that helper cell while the formula in J7 would have the simple formula IF(COUNTIF(I7,"x1"),"#A591",IF(COUNTIF(I7,"x2"),"#A665")). Your HLink_follow-routine would use the calculated address of that helper cell while the formula in J7 would have the simple formula =Hyperlink(H7, "See pic")

PS Yes, I am located in Europe - just look at my profile

Private Sub Worksheet_Change(ByVal Target As Range)
'auto selects cell

Dim MyVariable As String
MyVariable = Range("k8").Value
Application.Goto Reference:=Range(MyVariable)

End Sub

K8 contains a substitute formula to strip "#" from K7. Works as expected.

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