【问题标题】:Pick data from excel sheet ( vba )从 excel 表 (vba) 中选择数据
【发布时间】:2011-05-30 20:17:30
【问题描述】:

我有一个 Excel 工作表 name_data,工作表包含 3 列(A1=ID,B1=NAME AND C1=MARK) 我的疑问是,在 vba 用户表单中,我在 Combobox1 中输入或选择学生 ID,然后按命令按钮,它应该在 Textbox1 中显示学生姓名,在 Text2 中显示学生标记
数据存储在同一个excel表中,并在alt+F11中进入vba

请指教如何解决这个问题

【问题讨论】:

  • 你能在试图检索名称和标记的用户表单中显示你现有的代码吗?

标签: vba


【解决方案1】:

假设您在单元格 A1 到 C10 中有数据,第一行包含列名:

    A       B           C
1   ID      Name        Mark
2   1       Raj         50
3   2       Sulieman    45
4   etc...

在您的Userform 上,您有以下内容:

  • ComboBox1 - 包含 ID 列表
  • CommandButton1 - 点击此处获取学生信息
  • TextBox1 - 根据在 combobox1 中选择的 ID 显示学生的姓名
  • TextBox2 - 根据在 combobox1 中选择的 ID 显示学生的标记

在您的Userform 中,添加以下代码:

Private Sub UserForm_Initialize()
    Dim comboBoxItems As Range, Dim cl As Range

    Set comboBoxItems = Worksheets(1).Range("A2:A10")

    For Each cl In comboBoxItems //Populate combobox when userform launched
        Me.ComboBox1.AddItem (cl.Value)
    Next cl
End Sub

Private Sub CommandButton1_Click()
    Dim ID As Long
    Dim Name As String, Dim Mark As String, 
    Dim tableRng As Range

    Set tableRng = Worksheets(1).Range("A1:C10")

    ID = Me.ComboBox1.Value //Get ID selected in combobox
    Name = Application.WorksheetFunction.VLookup(ID, tableRng, 2, False)
    Mark = Application.WorksheetFunction.VLookup(ID, tableRng, 3, False)

    Me.TextBox1 = Name 
    Me.TextBox2 = Mark 
End Sub

【讨论】:

  • 没问题 - 很高兴能帮上忙。
猜你喜欢
  • 1970-01-01
  • 2013-10-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多