vba / excel - 根据用户输入到sheet1上的单元格,从sheet2中的值填充sheet1中的单元格

时间:2013-04-24 03:06:00

标签: excel excel-vba vba

我创建了一个通用的excel文件来帮助演示我正在做的事情。我命名为Tool.xlsm的文件包含两个工作表; Sheet1和Sheet2。 Sheet1将设计为具有几个将接受用户输入的字段。 Sheet2将对用户隐藏,但将包含各种下拉列表选择选项及其相应的描述,当选择特定代码时,这些选项应显示在Sheet1上的另一个单元格中。此外,Sheet2将在一列中包含多个ID#,并在下一列中包含相应的用户名。这样做的目的是使用户能够快速地将ID#与其所属的用户相关联。

到目前为止,这是我所拥有的......我怀疑我是否会像我应该的那样高效,但我非常感谢你所有人的专业知识!

Sub Button1_Click()

'Based on selected value of C1, show corresponding message in J1'
'Can this be done by simply referencing the code descriptions in sheet2?'

If Range("C1") = "code 1" Then
    Range("J1") = "code 1 description"
End If

If Range("C1") = "code 2" Then
    Range("J1") = "code 2 description"
End If

'End of code selection'
End Sub

Sub Button2_Click()

'Based on ID# entered into C3, display corresponding name in J1 (Sheet2 contains ID#s with corresponding names)'
'There has to be an esier way to loop through 1000s of records and display corresponding ID# and Person''s name'
'Rather than assigning Person 1, to Range J1, I should be able to just reference the cell Sheet2!E3 but that doesn''t seem to work'

If Range("C3") = "1001" Then
    Range("J1") = "Person 1"
End If

If Range("C3") = "34349090" Then
    Range("J1") = "Person 83"
End If

'End ID# search'
End Sub

Sub Button3_Click()

'Clear unlocked cells'

End Sub

my file in dropbox

2 个答案:

答案 0 :(得分:1)

致问:

  

这可以通过简单地引用sheet2中的代码描述来完成吗?

是。您可以使用VLOOKUP公式。

同样,您可以使用VLOOKUP公式根据ID返回名称。

例如,假设您的用户名在列K中,而ID在列J中:

在表单1上,假设单元格C3中的ID,输入公式:=VLOOKUP(C3, Sheet2!$J$K, 2, False)

答案 1 :(得分:0)

您可以使用worksheet_change事件。请设置rngFindCode&因此,rngFindCode1范围指的是sheet2中的数据。

以下是代码。

Private Sub Worksheet_Change(ByVal Target As Range)
    On Error Resume Next

    Application.EnableEvents = False

    If Target.Address = "$C$1" And Target.Cells.Count = 1 And Target.Value <> "" Then

        Dim rngFindCode As Range '
        Dim cellCode As Range

        Set rngFindCode = Sheets("Sheet2").Range("C1:C100")    ' Refers to range where code is in sheet 2
        Set cellCode = rngFindCode.Find(What:=Target.Value, LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByRows)

        If Not cellCode Is Nothing Then
            Range("J1").Value = cellCode.Offset(0, 1).Value
        End If

    ElseIf Target.Address = "$C$3" And Target.Cells.Count = 1 And Target.Value <> "" Then

        Dim rngFindCode1 As Range '
        Dim cellCode1 As Range

        Set rngFindCode1 = Sheets("Sheet2").Range("E1:E100")    'Refers to range where name is
        Set cellCode1 = rngFindCode1.Find(What:=Target.Value, LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByRows)

        If Not cellCode1 Is Nothing Then
            Range("J1").Value = cellCode1.Offset(0, 1).Value
        End If

    Else
        Range("J1").Value = ""
    End If

    Application.EnableEvents = True
End Sub