繁体   English   中英

excel宏可将单元格中的值添加到表中

[英]excel macro to add value from cell to a table

我希望每次单击按钮时都使用宏将工作表中某个单元格的值添加到另一个工作表中的表中。 例如,第一次按下按钮时,我希望工作表2中的单元格A1的值等于工作表1中的单元格C3,下次工作表2中的B1等于工作表1中的C3,依此类推。 如果要添加宏的单元格为空,则该宏仅应在表中添加一个值。

这是我到目前为止的内容:

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

任何帮助将不胜感激。

尝试下面的代码,一次更新一个单元格(当单元格为空时)

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

评论 :您也可以不使用.Value

尝试这个:

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

根据给出的新描述进行编辑

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM