vba 遍历文本框,然后将值放入一系列单元格中

vba loop through textboxes then place values in a range of cells

我有另一个关于 UserForms 中的循环和 TextBox 的新手场景。

这是我在单击 "Save" 命令按钮时想要完成的。

  1. 循环遍历名称以 "co" 开头并以数字 1-15 结尾的每个文本框。
  2. 如果该文本框中有值,代码会将该值添加到指定范围内的第一个单元格,然后移动到下一个文本框和单元格。

下面是包含单元格区域和用户表单的工作表图像。

WS 和用户窗体

我的代码是否正确?还是有没有循环的更有效的方法来做到这一点?提前感谢您对此的帮助。

Private Sub SandCont_Click()
    Dim wb As Workbook
    Dim wsJHA As Worksheet
    Dim wsRange1b As Range
    Dim wsRange1c As Range
    Dim wsRange2 As Range
    Dim wsRange3 As Range
    Dim wsRange4 As Range
    Dim wsRange5 As Range
    Dim wsRange6 As Range
    Dim wsRange7 As Range
    Dim wsRange8 As Range
    Dim wsRange9 As Range
    Dim wsRange10 As Range
    Dim c As Control
    Dim i As Integer    'used to loop through cells in ranges listed below???
    Dim x As String     'will be first two characters of textbox name
    Dim y As String     'will be last character of textbox name
    Dim z As Integer    'used to loop through textboxes on userform???

    Set wb = Application.ThisWorkbook
    Set wsJHA = wb.Sheets("JHA Keying")
    Set wsRange1b = wsJHA.Range("B4:B11")
    Set wsRange1c = wsJHA.Range("C4:C11")


    For Each c In Me.Controls
        If TypeName(c) = "TextBox" Then
            x = Left(c.Name, 2)
            y = Right(c.Name, 3)
            If x = "co" And y <= "015" Then
                wsRange1b.Value = c.Value
            End If
        End If
    Next c

'    Application.ThisWorkbook.Save

End Sub

您应该这样检查文本框的名称:

If c.Name Like "co*0[0-1][0-5]" Then...

解释:

  • co - 按字面意思匹配 'co'
  • * - 匹配任意数量的任意字符
  • 0 - 匹配零
  • [0-1] - 匹配 0 到 1
  • 范围内的数字
  • [0-5] - 匹配 0 到 5
  • 范围内的数字