Forum Discussion

StevieGis01's avatar
StevieGis01
Copper Contributor
Aug 18, 2020
Solved

Vba code help

Hi, I’ve been tasked with creating a parts spreadsheet in work, so for the past six weeks I have itemised over 2000 parts. After completing the data input I’ve set about making it more user friendly, ...
  • JMB17's avatar
    JMB17
    Aug 19, 2020

    StevieGis01 

     

    Cleaning up the code is often a matter of removing "select" and "activate" and joining whatever was selected/activated with the action. Instead of

     

    Range("A1").Select

    Selection.Value = 10

     

    it can be shortened to just

    Range("A1").Value = 10

     

    Just my two cents, but since these two procedures have a lot of overlap, you could set up a third procedure to do the work and just pass it the value by which to increase/decrease the cell. And, if you had cells other than F8 that this process worked on, you could pass it the applicable cell(s) on the Parts List worksheet.

     

    Or, you could have the user select the cells they want to increment/decrement and have the macro work on whatever range the user has selected?

     

    Public Sub MinusOnePartClickButtonTest()
         ChangePartCount -1
    End Sub
    
    Public Sub AddOnePartClickButtonTest()
         ChangePartCount 1
    End Sub
    
    Public Sub ChangePartCount(changeValue As Integer)
         Dim destWkSht As Worksheet
         Dim destCell As Range
         Dim timeStampCell As Range
         
         
         On Error GoTo ErrHandler
         
         
         If changeValue < 0 Then
              Set destWkSht = Sheets("Parts Removed")
         ElseIf changeValue > 0 Then
              Set destWkSht = Sheets("Parts Added")
         Else
              Exit Sub
         End If
         
         
         With destWkSht
              Set destCell = .Range("A" & .Rows.Count).End(xlUp).Offset(1)
              Set timeStampCell = Intersect(.Range("O:O").EntireColumn, destCell.EntireRow)
         End With
    
    
         With ThisWorkbook.Worksheets("Parts List")
              .Unprotect ("Password") ' Unlock Sheet
              .Range("F8").Value = .Range("F8").Value + changeValue
              .Range("A8,F8").Copy destCell
              .Protect ("Password") ' Lock Sheet
         End With
         
         timeStampCell.Value = Now
         
         Application.CutCopyMode = False
    
    
    ExitProc:
         Set destCell = Nothing
         Set destWkSht = Nothing
         Exit Sub
         
    ErrHandler:
         MsgBox "Error " & Err.Number & ": " & Err.Description
         Resume ExitProc
         
    End Sub

     

Resources