如何使用数据输入表格填写不同的Excel表格?

时间:2012-06-15 18:39:21

标签: excel vba excel-vba

我需要创建一个Excel解决方案来记录有关系列的数据。

  1. 表单应生成唯一代码(自动数字)以标识该记录。在这里,我询问父母的姓名,姓氏和出生日期。这是记录在一张表(称为Parents)。
  2. 一个家庭可以包含多个孩子,所以我认为这必须记录在另一张表(称为Children)上,与父母保持联系。
  3. 我能够将每个不同的字段保存到相应的单元格(映射)。这是我用来获取它的代码:

    Private Sub cmdSave_Click()
    ActiveWorkbook.Sheets("Parents").Activate
    Range("B2").Select
    Do
    If IsEmpty(ActiveCell) = False Then
        ActiveCell.Offset(1, 0).Select
    End If
    Loop Until IsEmpty(ActiveCell) = True
    
    'Father
    ActiveCell.Value = txtFatherFN.Text
    ActiveCell.Offset(0, 1) = txtFatherSN.Text
    ActiveCell.Offset(0, 2) = txtFatherLN.Text
    ActiveCell.Offset(0, 3) = txtFatherBirthDay.Text
    'Mother
    ActiveCell.Offset(0, 4) = txtMotherFN.Text
    ActiveCell.Offset(0, 5) = txtMotherSN.Text
    ActiveCell.Offset(0, 6) = txtMotherLN.Text
    ActiveCell.Offset(0, 7) = txtMotherBirthDay.Text
    Range("B2").Select
    End Sub
    

    所以,我需要一种方法来生成代码并保持与子代的关系。 欢迎任何帮助!

1 个答案:

答案 0 :(得分:0)

好。对我来说是缓慢的一天这是您为自己编写的代码。我还清理了一些原始代码,以提高效率。

Option Explicit

Private Sub cmdSave_Click()

Dim wks As Worksheet

Set wks = Sheets("Parents")

'assumes headers in First Row, ID is Column A
With wks

    'find next empty row
    Dim lngRow As Long
    lngRow = .Cells(Rows.Count, 1).End(xlUp).Offset(1).Row

    'find next unique Id
    Dim lngID As Long
    lngID = Application.WorksheetFunction.Max("A:A") + 1

    'id
    .Cells(lngRow, 1) = lngID
    'Father
    .Cells(lngRow, 2) = txtFatherFN.Text
    .Cells(lngRow, 3) = txtFatherSN.Text
    .Cells(lngRow, 4) = txtFatherLN.Text
    .Cells(lngRow, 5) = txtFatherBirthDay.Text
    'Mother
    .Cells(lngRow, 6) = txtFatherFN.Text
    .Cells(lngRow, 7) = txtFatherSN.Text
    .Cells(lngRow, 8) = txtFatherLN.Text
    .Cells(lngRow, 9) = txtFatherBirthDay.Text
End With

Set wks = Sheets("Children")

With wks

    'find next empty row
    lngRow = .Cells(Rows.Count, 1).End(xlUp).Offset(1).Row

    'need to adjust the for statement for however you collect your children in your form
    For Each Child In Children 'this is an example only to illustrate. You will need to change Child / Children to the objects used to collect the children info.
        .Cells(lngRow, 1) = Child
        lngRow = lngRow + 1
    Next

End With


End Sub