简体   繁体   English

如何在Excel VBA 4步骤中增加活动单元格?

[英]How to increment active cell in excel vba 4 steps?

I have a code which will enter data into a sheet. 我有一个将数据输入到工作表中的代码。 So once the data is entered, the form is reset and new data items can be entered. 因此,一旦输入了数据,便会重置表格并可以输入新的数据项。 But this new data items should be gone to sheet in such a way that each time there is change in position. 但是,这种新的数据项应该以每次位置发生变化的方式进行处理。 As in figure below, when i enter data using the form, it will get filled from B1 to D4 . 如下图所示,当我使用表格输入数据时,它将从B1填充到D4 Now I require the cell to be selected for next entry is F1 . 现在,我需要为下一个条目选择的单元格是F1 ie, next set of data has to be filled from F1 to H4 . 也就是说,必须从F1H4填充下一组数据。

见图片

I tried ActiveCell.Offset(0, 4).Select but it is taking me to cell T2 then next time to U2 and all 我尝试了ActiveCell.Offset(0, 4).Select但是它把我带到单元格T2然后下次带到U2和所有

Here is my code : 这是我的代码:

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

Text boxes are dynamically created 文本框是动态创建的

My form looks like this : 我的表格如下所示:

在此处输入图片说明

What has to be modified? 必须修改什么?

I suggest something like the following: 我建议如下所示:
It finds the last used column in row 2 and moves 2 right to get the first cell for the new data block. 它在第2行中找到最后使用的列,并向右移动2以获取新数据块的第一个单元格。 Note that for the first data block we need to move only one right. 注意,对于第一个数据块,我们只需要向右移动。

This example adds some sample data to the next empty block: 本示例将一些样本数据添加到下一个空白块:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM