将数据形成到特定单元格

Form Data to Particular Cells

在 Excel sheet2 中,A 和 D 列为名称,B 和 E 列为开始日期,C 和 F 列为结束日期,还有一个带有组合框(加载了名称)和两个文本框的表单。

我希望当我单击提交按钮时,它会在列中搜索与组合框值匹配的名称,然后将两个文本框的值写入右侧相邻的两个空单元格

         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 和 C 列中

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

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

这应该可以正常工作:

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