如何使用excel VBA在用户表单中显示所选数据

时间:2016-11-02 08:46:31

标签: vba excel-vba excel

我有一个代码,他选择了我想要的数据,但我想在表中显示这些数据,而不是在MsgBox中显示。

这是我的代码,我希望有人可以为我找到解决方案

Private Sub CommandButton1_Click()

Dim ws1 As Worksheet
Dim ws2 As Worksheet

Dim table1 As Range
Dim table2 As Range

Dim table1Rows As Integer
Dim table1Cols As Integer

Set ws1 = Worksheets("Feuil1")
Set ws2 = Worksheets("Feuil2")
Set table1 = ws1.Cells
Set table2 = ws2.Cells

table1Rows = ws1.UsedRange.Rows.Count
table1Cols = ws1.UsedRange.Columns.Count

For i = 1 To table1Rows
    For j = 1 To table1Cols
        If table1(i, 1).Value <> table2(i, 1).Value Then
            MsgBox "Libellé : " & table1(i, 1) & ", du montant : " & table1(i, 3) & " est ajouté !"
        End If
    Next
Next
End Sub

1 个答案:

答案 0 :(得分:0)

你需要的是ListBox。在其中创建UserForm(例如Userform1)和列表框(例如Listbox1)。然后,您可以通过此公式.AddItem函数将数据放入其中。你的循环看起来像:

For i = 1 To table1Rows
    For j = 1 To table1Cols
        If table1(i, 1).Value <> table2(i, 1).Value Then
            UserForm1.ListBox1.AddItem "Libellé : " & table1(i, 1) & ", du montant : " & table1(i, 3) & " est ajouté !"
        End If
    Next
Next
End Sub
UserForm1.Show