简体   繁体   中英

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.

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

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

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