如何在Excel VBA中的某个字段下直接添加Value?

时间:2014-03-19 16:32:38

标签: excel vba excel-vba

我有这段代码,但我想直接在" name"下添加名称等。在excel中,但到目前为止它只在第1行中添加它。有人可以帮助我吗?

例如,当我在名称框中输入内容时,我希望该值直接位于"名称"在Excel中,无论"名称"站在我的Excal表中。

我是新来的,这是我的第一个问题:)

'find first empty row in database
iRow = ws.Cells.Find(What:="Name", SearchOrder:=xlRows, _
    SearchDirection:=xlPrevious, LookIn:=xlValues).Row + 1
'check for a part number
If Trim(Me.TxtName.Value) = "" Then
  Me.TxtName.SetFocus
  MsgBox "Please enter a part number"
  Exit Sub
End If

'copy the data to the database
'use protect and unprotect lines,
'     with your password
'     if worksheet is protected
With ws
'  .Unprotect Password:="password"
  .Cells(iRow, 1).Value = Me.TxtName.Value
  .Cells(iRow, 2).Value = Me.TxtLocation.Value
  .Cells(iRow, 3).Value = Me.TxtDate.Value
  .Cells(iRow, 4).Value = Me.TxtQuantity.Value
' .Protect Password:="password"
End With
  • 感谢。

2 个答案:

答案 0 :(得分:1)

假设OP确实要填充第一个空行:

Dim pNum, rngName As Range

pNum = Trim(Me.TxtName.Value) 'check for a part number

If Len(pNum) = 0 Then
  Me.TxtName.SetFocus
  MsgBox "Please enter a part number"
  Exit Sub
End If

'find first empty row in database
Set rngName = ws.Cells.Find(What:="Name", SearchOrder:=xlRows, _
    SearchDirection:=xlPrevious, LookIn:=xlValues, LookAt:=xlWhole)

If Not rngName is Nothing then
  With ws.cells(rows.count, rngName.Column).End(xlUp).offset(1,0).entirerow
      .Cells(1).Value = pNum
      .Cells(2).Value = Me.TxtLocation.Value
      .Cells(3).Value = Me.TxtDate.Value
      .Cells(4).Value = Me.TxtQuantity.Value
  End With
Else
    msgbox "'Name' header not found!"
End if

答案 1 :(得分:0)

请尝试使用以下内容代替您发布的代码段。

Dim anchorCell As Range

'find first empty row in database
If ws.Cells(1,1).Value = "Name" Then
    Set anchorCell = ws.Cells(1,1)
Else
    Set anchorCell = ws.Cells.Find(What:="Name", SearchOrder:=xlRows, _
        SearchDirection:=xlNext, LookIn:=xlValues)
End If

If Not anchorCell Is Nothing Then
    'check for a part number
    If Trim(Me.TxtName.Value) = "" Then
      Me.TxtName.SetFocus
      MsgBox "Please enter a part number"
      Exit Sub
    End If
    'copy the data to the database
    'use protect and unprotect lines,
    '     with your password
    '     if worksheet is protected
    With anchorCell
    '  .Unprotect Password:="password"
      .Offset(1, 0).Value = Me.TxtName.Value
      .Offset(1, 1).Value = Me.TxtLocation.Value
      .Offset(1, 2).Value = Me.TxtDate.Value
      .Offset(1, 3).Value = Me.TxtQuantity.Value
    ' .Protect Password:="password"
    End With
End If