简体   繁体   中英

Copy and Paste as Value when any cell is clicked within a range of cells

I have a set of VBA codes that copy cell "AC14" in Sheet2 and paste as value to cell "Q4" in Sheet6. I have another set of code to apply a filter in Sheet6 when the value of cell "Q4" in Sheet6 changed, which I am happy about. The codes though not perfect it works to an extent. Below are my codes for the copy and paste part.

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

If Not Intersect(Range("AC14"), Target) Is Nothing Then
Range("AC14").Select
Selection.Copy
Sheet6.Activate
Sheet6.Range("Q4").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False
End If

End Sub

What I would like to improve upon are the following:

1) Change the Range("AC14") to a dynamic cell within a dynamic range in column "AC" starting from row 11 to a row number that changes from time to time. So that when I (or the user) click on any cell within this range the code will run correctly.

Notes: Sheet2 is a worksheet registering changes made to a project I am working on. Each row represents one change of my project and as time goes by the number of changes (rows) occurs could get up to 1500. Rows 1 to 10 of Sheet2 are allocated for column labels

2) When my cursor is on cell "AC14" in Sheet2, When I click on it again it doesn't take me to Sheet6. I understand this as it is not a change (in vba speakas the cursur is already there) in the worksheet. However, if I click on other cell and go back to click of cell "AC14" again, the codes will work. Is there a way around this?

I would grately appreciate it if anyone can shed me some light on how to solve the above issues. Thanks in advance.

Sean

Re item 2: It looks like you really need to define your requirements. Currently, you are using a Worksheet_SelectionChange event. By its very nature, the code will run when the selection is changed, either with the mouse or the keyboard. The code will NOT run if a cell that is already selected cell is clicked again with the mouse. Because that does not change the selection.

There are other events that you might want to employ, but none of them will work with just a single click on an already selected cell, so, in the truest sense of your question: no, there is not a workaround for that.

This might work for you:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

    If Target.Cells.CountLarge > 1 Then Exit Sub

    If Target.Row >= 14 And Target.Column = 29 and Target.Value <> "" Then

        Sheet6.Range("Q4").Value = Target.Value
        Target.Offset(0, -1).Select  'select the cell to the left
        Sheet6.Activate

    End If

End Sub

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