lundi 16 mars 2020

How to control the value of a Cell in Excel using an IF Then Statement in VBA

I am currently working on an excel application where I have a macro, operated by a button click, which resets the numerical values within certain cells in a table.

Within this table there are 3 columns; "Quantity Fitted (n)", "Quantity Required (m)" and "Lock Configuration".

What I need to happen, is when the button is clicked, the numerical values for each line within the "Quantity Fitted (n)" column are reset to match the values displayed within the "Quantity Required (m)" column of the same line.

However, if the cell value within the "Lock Configuration" column of that row is set to "locked", I want the "Quantity Fitted (n)" value to remain unchanged after the button click.

I hope this makes sense! Here's my current attempt to code this:

Public Sub Reset_Quantity_Fitted()
'Macro to make quantity fitted equal to quantity required

    Dim DatRange2 As String

    quantity_required = Worksheets(ActiveSheet.Name).ListObjects("Table_" & ActiveSheet.Name).ListColumns("Quantity Required (m)").DataBodyRange

    Set DatRange = Worksheets(ActiveSheet.Name).ListObjects("Table_" & ActiveSheet.Name).ListColumns("Quantity Fitted (n)").DataBodyRange
    DatRange2 = Worksheets(ActiveSheet.Name).ListObjects("Table_" & ActiveSheet.Name).ListColumns("Lock Configuration").DataBodyRange

    If DatRange2 = "Locked" Then
        DatRange = DatRange
    Else
        DatRange = quantity_required
    End If

End Sub

I don't think I'm too far away, but when running this code I get the following error:

Run-time error '13': Type mismatch

Any help is greatly appreciated! Thank you!

Aucun commentaire:

Enregistrer un commentaire