VBA在新行的空单元格中插入值

时间:2017-05-12 13:11:32

标签: excel vba excel-vba

已经谷歌搜索了3到4个小时但找不到任何有用的东西。

我想拥有什么以及已经做了什么:

If meinWert > 16000000 And meinWert < 20000000 Then
        Sheets("Aufträge").Cells(Rows.Count, 1).End(xlUp).Offset(1, 0) = Date
        Sheets("Aufträge").Cells(Rows.Count, 1).End(xlUp).Offset(0, 1) = meinWert
meinWert是扫描仪输入的一个订单号。上面的代码是已经运行的更大的代码的一部分。上面代码的结果如下: enter image description here

对于每个订单,有一些项目(从1到10个项目),现在我需要一个跳转到行“C”并插入项目代码的代码。就像我说的,每个订单有多个项目,因此每个项目(通过扫描仪输入)应该与正确的订单号列在同一行,如下所示: enter image description here

我想到了什么。像这样Sheets("Aufträge").Cells(Target.Row, 255).End(xlToLeft).Offset(0, 1),但它不起作用。

1 个答案:

答案 0 :(得分:1)

而不是你拥有的,你应该找出一次行,然后使用这一行将所有值插入其中:

Dim row As Long
Dim ws As Worksheet
Dim itemCount As Integer
Dim bolMoreItems As Integer

Set ws = Sheets("Aufträge")

If meinWert > 16000000 And meinWert < 20000000 Then
    bolMoreItems = True
    row = ws.Cells(Rows.Count, 1).End(xlUp).row + 1
    ws.Cells(row, 1) = Date
    ws.Cells(row, 2) = "test"

    itemCount = 1 'this isn't really needed except as a count to how many items there are.

    While bolMoreItems = True
        ws.Cells(row, 2 + itemCount) = "value" & itemCount 'instead of "value" & itemCount, put in whatever the value is.
         If there_are_no_more_items Then 'need some check to determine if there are more items....
             bolMoreItems = False
         End If

         itemCount = itemCount + 1

    Wend

End If

我已经为工作表使用了一个变量,以便于阅读和编码。显然,我不知道有多少项目,所以你需要做点什么来搞清楚。我也不知道你要插入新列的内容,所以留给你。

顺便说一下,这不适合你,因为Target是一个关键字。我不知道你的其余代码在做什么,但是在事件处理程序中使用它来指定触发事件的单元格。你可能没有这样的东西,所以这不行。你可以这样做,但它看起来像:

 Sheets("Aufträge").Cells(Sheets("Aufträge").Cells(Rows.Count, 1).End(xlUp).Row, 255) _
                 .End(xlToLeft).Offset(0, 1)

_只是继续下一行的陈述。这最终不清楚你要做什么,反正不是最好的解决方案。