简体   繁体   中英

Excel Sheet VBA code works on one but not the others

I've been working on a piece of VBA code that has caused me quite some pain. I'm trying to get this:

Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim numCell As Range

If Target.Count <> 1 Then Exit Sub

If Target.Value = "+" Then
    Set numCell = Target.Offset(0, -1)
    numCell.Select
    numCell.Value = numCell.Value + 1
ElseIf Target.Value = "-" Then
    Set numCell = Target.Offset(0, 1)
    numCell.Select
    numCell.Value = numCell.Value - 1
End If
    End Sub

to work on multiple different Excel sheets. For now, on one sheet (the original) it works perfectly. But then I copy-paste the layout of the first sheet to the next, and now the + and - don't work anymore on the new sheet.

Even by making the "Sub" private, it still doesn't change anything.

It is a simple add and subtract code that on each sheet should work in the same way.

Thanks for any advice you could give!

It should work if you copy this code to another sheet module. Open a blank workbook and add this code on more than one sheet's module to see if that works in the new workbook.

Though if you want to implement this code for all the sheets in the workbook, instead placing this code on specific sheet module, place it on ThisWorkbook Module.

The code will be as below...

Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)
Dim numCell As Range

If Target.Count <> 1 Then Exit Sub

If Target.Value = "+" Then
    Set numCell = Target.Offset(0, -1)
    numCell.Select
    numCell.Value = numCell.Value + 1
ElseIf Target.Value = "-" Then
    Set numCell = Target.Offset(0, 1)
    numCell.Select
    numCell.Value = numCell.Value - 1
End If

End Sub

The Worksheet_SelectionChange function must be placed in every sheet object which you want it to work for. I'm also concerned that you are causing a selection change within a sub which is triggered by a selection change - asking for an endless loop?!

Include this sub in every sheet

Sub Worksheet_SelectionChange(ByVal Target As Range)
    If Target.Count <> 1 Then Exit Sub      
    addsubtract Target
End Sub

Include this sub in one module

To create a module go to Insert>Module in the VBA editor.

Sub addsubtract(Target as Range)
    Dim numCell As Range
    If Target.Value = "+" Then
        Set numCell = Target.Offset(0, -1)
        numCell.Value = numCell.Value + 1
    ElseIf Target.Value = "-" Then
        Set numCell = Target.Offset(0, 1)
        numCell.Value = numCell.Value - 1
    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