表格数据到特定单元格

时间:2015-12-10 13:22:47

标签: excel vba excel-vba form-submit

在Excel sheet2中,我有列A& D代表名字,B& E开始日期和列C& F是结束日期和带有ComboBox(加载名称)和两个文本框的表单。

我想在单击“提交”按钮时,它将在列中搜索与ComboBox值匹配的名称,然后将两个TextBox的值写入右侧相邻的两个EMPTY单元格

enter image description here

         Private Sub CommandButton4_Click()
         Dim irow As Long
         Dim ws As Worksheet
         Set ws = Worksheets("Sheet2")
         With ws
      .Cells(.Rows.Count, "A").End(xlUp).Offset(1, 0).Value = Me.Combo.Value
    .Cells(.Rows.Count, "B").End(xlUp).Offset(1, 0).Value = Me.sttdate.value
    .Cells(Rows.Count, "C").End(xlUp).Offset(1, 0).Value = Me.enddate.Value
      End With
    With Me
    .Combo.Value = ""
    .startdate.Value = ""
    .enddate.Value = ""
    End With
    End Sub

此代码将所有形式的值添加到列A B& ç

2 个答案:

答案 0 :(得分:1)

这应该可以解决问题。我根据你在解释中写的内容添加了一些检查,以防万一。

Private Sub CommandButton4_Click()

Dim irow As Long
Dim ws As Worksheet
Set ws = Worksheets("Sheet2")

With ws

    irow = .Range("A" & .Rows.Count).End(xlup).Row

    Dim rFound as Range
    Set rFound = .Range("A1:A" & iRow).Find(Me.Combo.Value, lookat:=xlWhole)

    If not rFound is Nothing Then

       If IsEmpty(rFound.Offset(,1)) and IsEmtpy(rFound.Offset(,2)) Then 

           rFound.Offset(,1) = Me.sttdate.value
           rFound.Offset(,2) = Me.enddate.value

           With Me
              .Combo.Value = ""
              .startdate.Value = ""
              .enddate.Value = ""
           End With

       Else

           Msgbox "Name already has values"

       End If


   Else

       Msgbox "Name not Found"

   End If

  End Sub

答案 1 :(得分:0)

这应该可以正常工作:

Private Sub CommandButton4_Click()
Dim irow As Long, _
    wS As Worksheet, _
    NextRow As Long, _
    cF As Range

Set wS = Worksheets("Sheet2")
With wS
    With .Range("A:A")
        'First, define properly the Find method
        Set cF = .Find(What:=Me.Combo.Value, _
                    After:=.Cells(1, 1), _
                    LookIn:=xlValues, _
                    LookAt:=xlWhole, _
                    SearchOrder:=xlByRows, _
                    SearchDirection:=xlNext, _
                    MatchCase:=False, _
                    SearchFormat:=False)
    End With

    'If there is a result, keep looking with FindNext method
    If Not cF Is Nothing Then
        If cF.Offset(0, 1) <> vbNullString Then
            Set cF = cF.End(xlToRight).Offset(0, 1)
            cF.Value = Me.sttdate.Value
            cF.Offset(0, 1).Value = Me.EndDate.Value
        Else
            .Cells(cF.Row, "B").Value = Me.sttdate.Value
            .Cells(cF.Row, "C").Value = Me.EndDate.Value
        End If
    Else
        NextRow = .Cells(.Rows.Count, "A").End(xlUp).Offset(1, 0).Row
        .Cells(NextRow, "A").Value = Me.Combo.Value
        .Cells(NextRow, "B").Value = Me.sttdate.Value
        .Cells(NextRow, "C").Value = Me.EndDate.Value
    End If
End With

With Me
    .Combo.Value = ""
    .StartDate.Value = ""
    .EndDate.Value = ""
End With
End Sub