如何在excel vba 4步骤中增加活动单元?

时间:2018-03-16 07:46:11

标签: excel vba excel-vba

我有一个代码可以将数据输入到工作表中。因此,一旦输入数据,表格就会重置,并且可以输入新的数据项。但是这些新的数据项应该以每次位置发生变化的方式进入表格。如下图所示,当我使用表单输入数据时,它将从B1填充到D4。现在我要求为下一个条目选择单元格F1。即,必须从F1H4填充下一组数据。

See Image

我尝试了ActiveCell.Offset(0, 4).Select,但是它将我带到了T2,然后是U2和所有

这是我的代码:

Private Sub CommandButton1_Click()
Dim p As Long
Dim j As Integer
Dim erow As Long
Dim b As Integer
'erow = Sheet3.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
a = number
For p = 2 To number + 1

    Cells(p, 2) = Controls("txtBox" & p - 1).Text
    Cells(p, 3) = Controls("txtBox" & p + number - 1).Text
   Cells(p, 4) = Controls("txtBox" & p + number + number - 1).Text

Next p


'Cells(3, i) = TextBox1.Value
'Cells(4, i) = TextBox2.Value
'Cells(5, i) = TextBox3.Value
'Cells(3, i + 1) = TextBox4.Value
'Cells(3, i + 1) = TextBox4.Value

Call resetForm
ActiveCell.Offset(0, 4).Select

End Sub
  

动态创建文本框

我的表单如下:

enter image description here

需要修改什么?

1 个答案:

答案 0 :(得分:1)

我建议如下:
它找到第2行中最后一个使用的列,并向右移动2以获取新数据块的第一个单元格。请注意,对于第一个数据块,我们只需要向右移动一个。

此示例将一些示例数据添加到下一个空块:

Option Explicit

Private Sub CommandButton1_Click()
    Dim ws As Worksheet
    Set ws = Sheet3

    Dim LastCol As Long
    LastCol = ws.Cells(2, ws.Columns.Count).End(xlToLeft).Column 'get the last used column in row 2

    Dim FirstCellToWrite As Range
    If LastCol = 1 Then
        Set FirstCellToWrite = ws.Cells(2, LastCol + 1) 'first data block is different
    Else
        Set FirstCellToWrite = ws.Cells(2, LastCol + 2)
    End If

    'write example values
    FirstCellToWrite.Value = 1
    FirstCellToWrite.Offset(0, 1).Value = 2
    FirstCellToWrite.Offset(0, 2).Value = 3
    FirstCellToWrite.Offset(1, 0).Value = 4
    FirstCellToWrite.Offset(1, 1).Value = 5
    FirstCellToWrite.Offset(1, 2).Value = 6
    FirstCellToWrite.Offset(2, 0).Value = 7
    FirstCellToWrite.Offset(2, 1).Value = 8
    FirstCellToWrite.Offset(2, 2).Value = 9
End Sub