Question

I have an Excel project which contains 3 worksheets, namely "Unhealthy Foods" "Healthy Foods" and "Meal"

The two food tables contain a list of foods along with their their fat, protein and carbohydrate content. Using that data, their calories per 100 grams are also calculated. These foods are divided into 3 sub-headings: Foods, snacks and drinks. I want to create a macro which will be launched using an "Add to Meal" button next to each food item on each table which will copy the row's content to the first available row in the "Meal" class.

Is it possible for this to be done? If so, how?

Was it helpful?

Solution

The issue (in my opinion) with using buttons to refer to cells on a worksheet is that buttons are objects on the worksheet which makes getting their position in terms of column / row quite tricky.

Here is the brute force approach if you want to use buttons. Suppose in Healthy Foods you have the folllowing:

     A         B      C          D
1    Item      Fat    Protein    Sugar
2    Apple     0      50         5       |Add To Menu|  <-- this is a commandbutton called **Apple**
3    Snickers  100    0          100     |Add to Menu|  <-- this is a commandbutton called **snickers**

The following code will copy the details to next available row in Meal (NB - I assume Meal is same table format as shown above)

Private Sub Apple_Click()
    AddMealToMenu Range("A2") //For each button you must specify range where item is in table
End Sub

Sub AddMealToMenu(ref As Range)
    Dim mealItem As Range
    Set mealItem = Range(ref, ref.Offset(0, 3))
    mealItem.Copy Destination:=GetNextFreeRow
End Sub

Function GetNextFreeRow() As Range
    With Worksheets("Meal")
        If .Range("A2") = vbNullString Then
            Set GetNextFreeRow = .Range("A2")
        Else
            Set GetNextFreeRow = .Range("A1").End(xlDown).Offset(1, 0)
        End If
    End With
End Function

For Snickers you would need to add simialr code for Apple i.e.

Private Sub Snickers_Click()
    AddMealToMenu Range("A3")
End Sub

If this works for you, fine, but it may take some setting up and is a brute force approach.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top