使用宏更新数据

时间:2014-07-17 07:20:30

标签: excel excel-vba vba

我想将工作表中记录的数据更新到另一个工作表中的另一个主副本。我的问题是我如何制作它,以便我可以在工作表上记录并更新,因为我想要它? 截至目前,我只能更新最后一行,即使我更改了代码中的行号。知道为什么以及如何解决它?

以下代码

Private Sub CommandButton1_Click()


Dim Name As String
Dim Problem As Integer


Worksheets("Sheet1").Select
Name = Range("C4")
Problem = Range("D4")
Worksheets("Sheet2").Select
Worksheets("Sheet2").Range("B4").Select
If Worksheets("Sheet2").Range("B4").Offset(1, 0) <> "" Then
Worksheets("Sheet2").Range("B4").End(xlDown).Select
End If
ActiveCell.Offset(1, 0).Select
ActiveCell.Value = Name
ActiveCell.Offset(0, 1).Select
ActiveCell.Value = Problem
Worksheets("Sheet1").Select
Worksheets("Sheet1").Range("C4").Select
End Sub

Sheet1:我插入新数据并按更新。这会将值发送到表2

enter image description here

表2:数据在此处更新。我想举例来说,回到这个列表的中间并编辑其中一个,例如jo的条目。

enter image description here

1 个答案:

答案 0 :(得分:1)

现在我明白了:)

Private Sub CommandButton1_Click()

Dim Name As String
Dim Problem As Integer
Dim Source As Worksheet, Target As Worksheet
Dim ItsAMatch As Boolean
Dim i As Integer

Set Source = ThisWorkbook.Worksheets("Sheet1")
Set Target = ThisWorkbook.Worksheets("Sheet2")
Name = Source.Range("B5")
Problem = Source.Range("C5")

Do Until IsEmpty(Target.Cells(5+i,2)) ' This will loop down through non empty cells from row 5 of column 2 
    If Target.Cells(5+i,2) = Name Then
        ItsAMatch = True 
        Target.Cells(5+i,3) = Problem ' This will overwrite your "Problem" value if the name was already in the column
        Exit Do
    End If
    i = i+1
Loop

' This will write new records if the name hasn't been already found
If ItsAMatch = False Then
    Target.Cells(5,2).End(xlDown).Offset(1,0) = Name
    Target.Cells(5,2).End(xlDown).Offset(0,1) = Problem
End If

Set Source = Nothing
Set Target = Nothing

End Sub

这未经测试但应该有效