VBA中的组合框和文本框等于Excel中的单元格

时间:2018-08-02 08:30:38

标签: excel vba

我有一个数据库 Database 和我的代码如下。我可以调出txtnumber中显示的数据,但不是正确的数据。另外,如果我在其中添加msg框,则msg框将继续循环播放,并且txtnumber中的数据也会更改。

有人知道发生了什么并协助纠正我的代码吗?

Dim sht As Worksheet 
Dim i As Long 
Dim j As Long 
Dim LastRow As Long 
Dim LastColumn As Long 

Set sht = ThisWorkbook.Worksheets("Sheet1") 

LastRow = sht.Range("A" & Rows.Count).End(xlUp).Row 
LastColumn = sht.Range("B" & Rows.Count).End(xlUp).Row 

For i = 2 To LastRow 
    For j = 3 To LastColumn 

    With Me 
        MsgBox ("Hello") 
        If sht.Cells(i, "A").Value = Val(.ComboBox1) And sht.Cells(j, "B").Value = Val(.txtgender) Then 
            .txtnumber = sht.Cells(j, "C").Value 
        End If 
    End With 
    Exit For
    Next j 
Next i 

1 个答案:

答案 0 :(得分:0)

这是一种与您尝试的解决方案有些相似的解决方案。我扔掉LastRow并使用了LastColumn,这样您就可以看到我试图指向您的位置。本示例使用了许多您遵循的相同原理,但不是我的首选方法。合并的单元会增加复杂性,您将在继续之前以不同的方式从解决此问题中受益。额外的练习还将帮助您理解嵌套循环。

Private Sub CommandButton1_Click()
    Dim sht As Worksheet
    Dim i As Long
    Dim j As Long
    Dim LastColumn As Long
    Set sht = ThisWorkbook.Worksheets("Sheet1")
    With sht
        LastColumn = .Cells(4, .Columns.Count).End(xlToLeft).Column
        For i = 2 To LastColumn Step 2
            If .Cells(4, i + j) = ComboBox1.Value Then
                For j = 0 To 1
                    If Cells(5, i + j) = ComboBox2.Value Then ComboBox3.Value = .Cells(6, i + j)
                Next
            End If
        Next
    End With
End Sub