从预定义行和列范围中检索值

时间:2017-10-24 15:35:44

标签: excel-vba vba excel

如何从预定义行和列范围(增量)中检索值到文本框(增量),以便例如单元格“J4”的值填充在" textbox1"及其标题为" Label1" ,单元格“k4”的值填充在" textbox2"它的列标题为" Label2"等等......单元格“BG4”的值填充在" textbox50"及其标题为" Label50"。

我尝试了以下

Private Sub CommandButton1_Click()
    Dim i As Long, lastrow As Long
    Dim ws As Worksheet
    Dim fcolumn As Long
    Dim lcolumn As Long
    Set ws = Worksheets("md")
    lastrow = ws.Cells.Find(What:="*",         
    SearchOrder:=xlRows,SearchDirection:=xlPrevious, LookIn:=xlValues).Row + 1

    fcolumn = 9
    lcolumn = 50
    For i = 2 To lastrow
        fcolumn = fcolumn + 1
        If ws.Cells(i, "A").Value = Val(Me.TextBox_orderno) Then
            If Sheets("md").Cells(i, fcolumn).Value <> 0 Then
                Me.Label1 = ws.Cells(2, fcolumn)
                Me.TextBox1 = Sheets("md").Cells(i, fcolumn).Value
            End If
        If Sheets("md").Cells(i, fcolumn).Value <> 0 Then
            Me.Label2 = ws.Cells(2, fcolumn)
            Me.TextBox1 = Sheets("md").Cells(i, fcolumn).Value
        End If
    Next
End Sub

1 个答案:

答案 0 :(得分:0)

我仍然不确定你到底在做什么,但看看这对你有帮助。它至少应该向您展示如何动态引用仅在最后的数字中改变的控件的名称。

Private Sub CommandButton1_Click()

Dim i As Long, lastrow As Long
Dim ws As Worksheet
Dim fcolumn As Long
Dim lcolumn As Long

Set ws = Worksheets("md")

lastrow = ws.Cells.Find(What:="*", SearchOrder:=xlRows, SearchDirection:=xlPrevious, LookIn:=xlValues).Row + 1

fcolumn = 9
lcolumn = 50

For i = 2 To lastrow
    fcolumn = fcolumn + 1
    If ws.Cells(i, "A").Value = Val(Me.Controls("TextBox" & i - 1)) Then
        If Sheets("md").Cells(i, fcolumn).Value <> 0 Then
            Me.Controls("Label" & i - 1).Value = ws.Cells(2, fcolumn)
            Me.Controls("Textbox" & i - 1).Value = Sheets("md").Cells(i, fcolumn).Value
        End If
    End If
Next

End Sub