首页 > 解决方案 > 通过组合框从多个工作表中获取数据,以在用户窗体 vba 的多个文本框中输入

问题描述

我目前正在想出一个用户表单来从多个工作表中获取成本指数数据,以便在多个文本框中输入。我的工作簿中有 6 个工作表,分别称为 CPI、LME、钢价 CRUSpi、CEPCI、PPI 和日期。

在我的用户表单中,有 3 个命令按钮 Close_Click 用于关闭工作簿,Search_Click 用于搜索多个工作表中的数据,Reset_Click 用于重置用户表单。有 10 个文本框 TextBox_PPI 用于输出 PPI 工作表中的数据,TextBox_CPI 用于输出 CPI 工作表中的数据,TextBox_Copper 和 TextBox_Aluminium 用于输出 LME 工作表中的数据,TextBox_stainless_steel、TextBox_global_steel、TextBox_asia_steel、TextBox_north_america_steel 和 TextBox_europe_steel 用于将钢价 CRUSpi 工作表中的数据输出为以及 TextBox_CEPCI 从 CEPCI 工作表输出数据。此外,还有 3 个组合框 ComboBox_Date 列出了日期工作表中的日期,ComboBox_CPI 和 ComboBox_PPI 分别列出了 CPI 和 PPI 工作表中的国家/地区。

我想要的是不同的文本框通过单击组合框 ComboBox_Date 中的不同日期来输出来自不同工作表的数据。除了点击日期,我还需要点击组合框 ComboBox_CPI 和 ComboBox_PPI 中的不同国家来分别输出文本框 TextBox_CPI 和 TextBox_PPI 中的数据。我已经设法在组合框中提出日期和国家/地区列表,但是当我尝试运行用户表单时,文本框中没有输出任何数据。附上我的 VBA 代码片段:

Private Sub Close_Click()
    Unload Me
End Sub

Private Sub Search_Click()
Dim sh As Worksheet
Dim sh1 As Worksheet
Dim sh2 As Worksheet
Dim sh3 As Worksheet

Set sh = ThisWorkbook.Sheets("PPI")
Set sh1 = ThisWorkbook.Sheets("CPI")
Set sh2 = ThisWorkbook.Sheets("LME")
Set sh3 = ThisWorkbook.Sheets("Steel Price CRUSpi")

Dim ppirow, cpirow, lmerow, steelrow As Long
'Last row of every worksheets containing dataFir
ppirow = sh.Range("A" & Rows.Count).End(xlUp).Row
cpirow = sh1.Range("A" & Rows.Count).End(xlUp).Row
lmerow = sh2.Range("A" & Rows.Count).End(xlUp).Row
steelrow = sh3.Range("A" & Rows.Count).End(xlUp).Row

'Ensure date is filled up, if not prompt
If Me.ComboBox_Date.Value = "" Then
    MsgBox "Please enter a valid date"
End If

'Look for copper and aluminium indices
Dim i As Long
For i = 2 To lmerow
    If Me.ComboBox_Date.Value = sh2.Cells(i, "A") Then
        Me.TextBox_Copper = sh2.Cells(i, "B").Value
        Me.TextBox_Aluminium = sh2.Cells(i, "G").Value
    End If
Next i

End Sub


Private Sub Reset_Click()
Dim z As Control
For Each z In UserForm1.Controls
    If TypeName(z) = "TextBox" Then
        z.Value = ""
    End If
Next z
End Sub


Private Sub UserForm_Initialize()
Dim sh As Worksheet
Dim sh1 As Worksheet
Dim sh2 As Worksheet

Set sh = ThisWorkbook.Sheets("PPI")
Set sh1 = ThisWorkbook.Sheets("CPI")
Set sh2 = ThisWorkbook.Sheets("Date")

Dim i As Integer
Dim d As Integer

'List of country with PPI indices
For i = 4 To Application.WorksheetFunction.CountA(sh.Range("1:1"))
    Me.ComboBox_PPI.AddItem sh.Cells(1, i).Value
Next i

'List of country with CPI indices
For i = 4 To Application.WorksheetFunction.CountA(sh1.Range("1:1"))
    Me.ComboBox_CPI.AddItem sh1.Cells(1, i).Value
Next i

'Date input
d = 1

Do
    DoEvents
    d = d + 1
    With Me.ComboBox_Date
        .AddItem sh2.Range("A" & d)
    End With
Loop Until sh2.Range("A" & d) = ""

End Sub

很抱歉,由于我的声誉点低,我无法嵌入图片。任何帮助深表感谢

标签: excelvbacomboboxtextbox

解决方案


推荐阅读