在for-each循环中复制动态范围

时间:2017-11-28 18:12:43

标签: excel vba excel-vba foreach copy-paste

我花了几个星期的时间试图从其他建议中拼凑出一块坚实的VBA来完成这项任务,但现在我转向大家寻求答案。我试图复制范围从ws2,列A:K的行开始,其中值c匹配ws1中的值i到以ws1中的值i开头的行。复制的标准是1和0。它基本上是一个美化的循环v-lookup,可以粘贴一个动态范围。

我想出了循环机制,现在我只需要帮助编写复制所选单元格的代码。

这是我到目前为止所拥有的:

For Each i In ws1.Range("A4:A26")
    For Each c In ws2.Range("A8:A28")
        If i.Cells.Value <> c.Cells.Value Then
            'select columns A:K in the row with the value c in ws2
            'open ws1
            'paste selection to[starting at] column D in ws1
            Exit For

        End If
    Next c
Next i

2 个答案:

答案 0 :(得分:0)

不确定这是否是您的目标。如果您可以通过“选择行,以Ws1中的值c开头的列A:K”来澄清您的意思,这可能会有所帮助。我假设Exit For是值,如果值不匹配,您希望在执行i语句中的所有操作后转到下一个If

使用“录制宏”功能可能会有所帮助。

For Each i In ws1.Range("A4:A26")
    For Each c In ws2.Range("A8:A28")
        If i.Cells.Value <> c.Cells.Value Then
            'select the row, columns A:K that starts with the value c in ws2
            ws2.Range(Cells(c.Cells.Value, "A"), Cells(c.Cells.Value, "K")).Copy
            'open ws1
            ws1.Activate
            'paste selection, starting from column D in ws1, into ws1
            ws1.Cells(i.Cells.Value, "D").Select
            ActiveSheet.Paste
            Exit For
        End If
    Next c
Next i
End Sub

答案 1 :(得分:0)

如果你真的想要比赛,一旦找到比赛,然后退出For 这样做不需要激活或选择

echo "Enter the file name: " 
read file

echo "Count lines, words, characters or all three (l, m, c, a)? "
read variable

NUMOFLINES=$(wc -l < $file)
NUMOFWORDS=$(wc -w < $file)
NUMOFCHARACTERS=$(wc -c < $file)

if [ $variable == "l" ]
    then
        echo "The file" $file "has" $NUMOFLINES "lines"

elif [ $variable == "m" ]
    then

        echo "The file" $file "has" $NUMOFWORDS "words"

elif [ $variable == "c" ]
    then

        echo "The file" $file "has" $NUMOFCHARACTERS "characters"

elif [ $variable == "a" ]
    then
        echo "The file" $file "has" $NUMOFLINES "lines"
        echo "The file" $file "has" $NUMOFWORDS "words"
        echo "The file" $file "has" $NUMOFCHARACTERS "characters"

elif [ $variable != "*" ] #|| [ $variable != "m" ] || [ $variable != "c" ] || 
[ $variable != "a" ]
    then
        echo "Invalid input"

    fi