我有一个带有500多个文本框的用户窗体,应该从某些工作表上的某些单元格中填充。我指的是纸张和单元格的部分很清楚。但我不知道如何填写500多个文本框,而不是逐个引用它们。
我不想这样做:
Textbox1.value = sheet1.cells(x,y)
Textbox2.value = sheet1.cells(x+1,y)
.
.
.
我想这样做:
Textbox(x).value = sheet1.cells(x,y)
当然是循环
我试过了:
Private Sub UserForm_Activate()
Dim s As String
Dim m As Integer
Dim k As Integer
Dim l As Integer
s = "TextBox1"
For k = 1 To 10
s.Value = Sayfa9.Cells(l, m)
s = Replace(s, k, k + 1)
m = m + 1
Next k
end sub
当然s.Value是错的。我该怎么做?
答案 0 :(得分:0)
您可以遍历此窗体中的所有控件,检查它们是否为TextBoxes,从其名称中获取TextBox的编号,然后根据需要设置其值。
像这样:
Private Sub UserForm_Activate()
y = 1
For Each oControl In Me.Controls
If oControl.Name Like "TextBox*" Then
x = Right(oControl.Name, Len(oControl.Name) - 7) 'TextBox123
'1 7 10=Len()
oControl.Value = ThisWorkbook.Sheets(1).Cells(x, y)
End If
Next
End Sub
答案 1 :(得分:0)
如果您有固定数量的文本框,则可以使用以下代码:
Private Sub UserForm_Activate()
Dim i As Integer
Dim j As Integer
j = 1 'set it to the required column number
For i = 1 To 500 'set 500 to the maximum no. of textboxes
Controls("TextBox" & i).Value = ThisWorkbook.Sheets("Sheet1").Cells(i, j)
Next i
End Sub
答案 2 :(得分:0)
这是我根据需要修改的代码。谢谢腊斯克和阿克塞尔。 Axel的答案有更多深度。我相信我以后会把它作为基础。 Fumu的回答也很深刻。谢谢大家。
Private Sub UserForm_Activate()
Dim i As Integer
Dim j As Integer
Dim k As Integer
j = 138 'set it to the required column number
k = 19
For i = 1 To 187 'set 500 to the maximum no. of textboxes
If j = 149 Then
j = 138 'this resets the column number to beginning
If k = 30 Then k = 37 'this skips the gap in the table
k = k + 1 'this incements the row number to the next row
End If
Controls("TextBox" & i).Value = Sheet9.Cells(k, j)
j = j + 1 'this increment column number to next
Next i
End Sub
答案 3 :(得分:-1)
您可以作为worksheet.shapes.item的成员访问每个文本框。
以下代码可能会将单元格(x,y),单元格(x + 1,y)...的值分配给工作表中的文本框。
Sub SetValueToTextboxes(x,y)
Dim i As Integer, dim j as Integer
With ActiveSheet.Shapes
j=0
For i = .Count To 1 Step -1
If .Item(i).Type = msoTextBox Then 'set data if the shape is 'textbox'
.Item(i).TextFrame.Characters.Text = .cells(x+j,y).value
j=j+1
End If
Next i
End With
End Sub
我希望你能对处理文本框有所了解。