Tony Davis
Tony Davis

Reputation: 67

excel macro to add value from cell to a table

I am looking to use a macro to add the value of a certain cell in a worksheet to a table in another worksheet each time each time a button is pressed. For example, the first time the button is pressed I want the value of cell A1 in worksheet2 to be equal to cell C3 in worksheet1, next time B1 in worksheet2 is equal to C3 in worksheet1 , and so on. The macro should only add a value to the table if the cell thst it's being added to is empty.

This is what I have so far:

Sub Button32_ClickandUpdate
    myVariable = Worksheets("Worksheet1").Range("C3")

    For i = 1 To 6
        If IsEmpty(Cells(1, i)) Then
            Worksheets("Worksheet2").Range(Cells(1,i)) = myVariable
            Exit Sub
        End If
    Next i
End Sub

Any help would be greatly appreciated.

Upvotes: 0

Views: 1355

Answers (2)

Shai Rado
Shai Rado

Reputation: 33682

Try the code below, to update one cell at a time (when cell is empty)

Sub Button32_ClickandUpdate()

    For i = 1 To 6
        If IsEmpty(Sheets("Worksheet2").Cells(1, i).Value) Then
            Sheets("Worksheet2").Cells(1, i).Value = Sheets("Worksheet1").Range("C3").Value                
            Exit Sub
        End If
    Next i

End Sub

Comment: you can use this also without the .Value

Upvotes: 1

b1919676
b1919676

Reputation: 110

Try this:

Sub Button32_ClickandUpdate
    myVariable = Worksheets("Worksheet1").Range("C3")

    For i = 1 To 6
        If IsEmpty(Worksheets("Worksheet2").Cells(1, i)) Then
            Worksheets("Worksheet2").Cells(1, i) = myVariable
            'Exit Sub (remove or comment this line to update all cells at the sime time)
        End If
    Next i
End Sub

Edit According to new description given:

Sub Button32_ClickandUpdate
    myVariable = Worksheets("Worksheet1").Range("C3")

        i = 1
        While i < 7
            If IsEmpty(Worksheets("Worksheet2").Cells(1, i)) Then
                Worksheets("Worksheet2").Cells(1, i) = myVariable
            End If
            i = i + 1
        Wend
End Sub

Upvotes: 0

Related Questions