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

时间:2018-08-08 19:38:21

标签: excel vba excel-vba excel-2013

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

这是单击“保存”命令按钮时我要完成的工作。

  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

1 个答案:

答案 0 :(得分:0)

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

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

说明:

  • co <​​/ strong>-从字面上匹配“ co”
  • * -匹配任意数量的任意字符
  • 0 -匹配零
  • [0-1] -匹配范围从0到1的数字
  • [0-5] -匹配介于0到5之间的数字