使用VBA-Excel获取工作表上的值ID以编辑或更新另一工作表中列表中的数据

时间:2019-06-07 03:36:00

标签: excel vba

关于该问题,如何通过vba-excel用按钮更新单元格ID是否为真,所以我需要将表1的某些值从表列更新为另一表的数据列表。

例如:

在Sheet1中(编辑或更新单元格的任何值)

enter image description here

在Sheet2中(如果ID为true,则更新数据)

enter image description here

Sub update()
Dim LR1 As Long
With Sheets("Sheet2")
    LR1 = .Range("A" & .Rows.Count).End(xlUp).Row
    .Range("A" & LR1) = Sheets("Sheet1").Range("B2")
    .Range("B" & LR1) = Sheets("Sheet1").Range("B3")
    .Range("C" & LR1) = Sheets("Sheet1").Range("B4")
    .Range("D" & LR1) = Sheets("Sheet1").Range("B5")
End With
End Sub

我希望有人能帮助我解决问题

1 个答案:

答案 0 :(得分:2)

使用Find()找到匹配的行(如果存在),然后更新该行:如果找不到,则添加新行

Sub update()
Dim f As Range, sht1 As Worksheet
Set sht1 = Sheets("Sheet1")

With Sheets("Sheet2")
    Set f = .Range("A:A").Find(what:=sht1.Range("B1").Value, lookat:=xlWhole)
    If f Is Nothing Then Set f = .Range("A" & .Rows.Count).End(xlUp).Offset(1, 0)
    f.Resize(1, 5).Value = Application.Transpose(sht1.Range("B1:B5").Value)
End With
End Sub

编辑:如果需要更多控制,则逐个单元

Sub update()

    Dim f As Range, sht1 As Worksheet
    Set sht1 = Sheets("Sheet1")

    With Sheets("Sheet2")
        Set f = .Range("A:A").Find(what:=sht1.Range("B1").Value, lookat:=xlWhole)
        If f Is Nothing Then Set f = .Range("A" & .Rows.Count).End(xlUp).Offset(1, 0)
        With f.EntireRow
            .Cells(1).Value = sht1.Range("B1").value
            'skip one cell then copy the rest...
            .Cells(3).Resize(1, 4).Value = Application.Transpose(sht1.Range("B4:B5").Value)
            'etc etc
        End With

    End With

End Sub