Excel VBA - 直到空白单元格

时间:2017-09-21 20:52:24

标签: excel vba excel-vba

我正在录制宏并需要一些帮助。我想将“SalesData”工作表的G列中的值复制并粘贴到“结果”工作表的单元格A2,A12,A22等中,直到G列中没有更多值。

VBA对我来说很新,我尝试过使用Do / Until,但一切都崩溃了。请你帮助我好吗?请参阅下面我记录的代码。谢谢!

Sub(x)

 Sheets("SalesData").Select
    Range("G2").Select
    Selection.Copy
    Sheets("Results").Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False

    Range("A12").Select
    Sheets("SalesData").Select
    Range("G3").Select
    Application.CutCopyMode = False
    Selection.Copy
    Sheets("Results").Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False

    Range("A22").Select
        Sheets("SalesData").Select
    Range("G4").Select
    Application.CutCopyMode = False
    Selection.Copy
    Sheets("Results").Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False

        Range("A32").Select
        Sheets("SalesData").Select
    Range("G5").Select
    Application.CutCopyMode = False
    Selection.Copy
    Sheets("Results").Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False

End Sub 

3 个答案:

答案 0 :(得分:3)

我更喜欢先找到列中的最后一个单元格,然后使用For循环。

由于您只是在做值,我们可以避免使用剪贴板并直接赋值。

由于您每隔10个单元格进行粘贴,我们可以使用单独的计数器向下移动10个循环。

Sub x()
Dim ws As Worksheet
Dim lst As Long
Dim i As Long, j As Long
'use variable to limit the number of times we type the same thing
Set ws = Worksheets("Results")
'First row of the output
j = 2
'using with and the "." in front of those items that belong to it also limits the typing.
With Worksheets("SalesData")
    'Find the last row with values in Column G
    lst = .Cells(.Rows.Count, 7).End(xlUp).Row
    'Loop from the second row to the last row.
    For i = 2 To lst
        'Assign the value
        ws.Cells(j, 1).Value = .Cells(i, 7).Value
        'Move down 10 rows on the output
        j = j + 10
    Next i
End With

End Sub

答案 1 :(得分:2)

这是相同的事情,但使用范围变量

input=[[1,2,3],[4],[5,6]]
all_lists=[]

for i in xrange(len(input)):
    all_lists.append(list(itertools.permutations(input[i])))

all_combinations = list(itertools.product(*all_lists))

## concat them together
combinations_combined = [list(itertools.chain(*a)) for a in all_combinations]

答案 2 :(得分:1)

这只是为了另一种方式的乐趣/练习:

Sub copyFromG()
Dim copyRng As Range, cel As Range
Dim salesWS As Worksheet, resultsWS As Worksheet

Set salesWS = Sheets("SalesData")
Set resultsWS = Sheets("Results")

Set copyRng = salesWS.Range("G2:G" & salesWS.Range("G2").End(xlDown).Row) ' assuming you have a header in G1

For Each cel In copyRng
    resultsWS.Range("A" & 2 + 10 * copyRng.Rows(cel.Row).Row - 30).Value = cel.Value
Next cel

End Sub