VBA从单元格中查找数据并更新旧数据

时间:2014-01-13 16:13:02

标签: vba excel-vba excel

我正在尝试获取替换数据的代码。这是我的情景。在sheet2中,我的数据A2到底部是月(1,2,3),B2在它的年份(2012)和在c2,d2,e2是数值数据(200,150,50)

现在,在sheet1中,我有一个用于下拉列表的表A22来选择月/季。 B22一年。 C22:E22用于编辑选定的月份和年份数值数据。

在Sheet1中如果我选择A22-April B22-2012并在C22:E22中输入新值并单击编辑按钮。我希望看到先前输入值的工作表2表中的反映更改。

Sub edit() 

Dim s1 As Worksheet, s2 As Worksheet 
Set s1 = Sheets("Sheet1") 
Set s2 = Sheets("Sheet2") 
v1 = s1.Range("A22") 
v2 = s1.Range("B22") 
v3 = s1.Range("C22") 
v4 = s1.Range("D22") 
v5 = s1.Range("E22") 
s2.Activate 
For Each r In Intersect(ActiveSheet.UsedRange, Range("A:E")) 
If r.Value = v1 Then 
r.Offset(0, 1).Value = v2 
r.Offset(0, 2).Value = v3 
End If 
Next 

Worksheets("Sheet1").Range("A22:E22").ClearContents 

End Sub

任何帮助将不胜感激。谢谢!

1 个答案:

答案 0 :(得分:0)

这样的事情:

Sub SaveEdit() 

Dim s1 As Worksheet, s2 As Worksheet
Dim bFound as boolean, r as Range 

Set s1 = Sheets("Sheet1") 
Set s2 = Sheets("Sheet2") 

v1 = s1.Range("A22") 
v2 = s1.Range("B22") 
v3 = s1.Range("C22") 
v4 = s1.Range("D22") 
v5 = s1.Range("E22") 

If v1<>"" and v2<>"" Then
    For Each r In Intersect(s2.UsedRange, s2.Range("A:E")).Rows 
      If r.cells(1).Value = v1 and r.cells(2).Value=v2 Then 
        r.cells(3).Value = v3 
        r.cells(4).Value = v4
        r.cells(5).Value = v5
        bFound = True
        s1.Range("A22:E22").ClearContents
      End If 
    Next
    If Not bFound then msgbox "No match found for this record!"
Else
    msgbox "both Year and Month are required!"
End If


End Sub