Excel VBA:复制/粘贴循环

时间:2017-03-28 09:39:29

标签: excel vba excel-vba loops

我在这个留言板上进行了广泛搜索,但没有找到可行的答案。我是VBA的初学者,但我已尽力了。

背景:我有一个从外部来源更新的数据块(Bloomberg,对问题不重要)。我想循环一个驱动数据更新的输入(公司的股票代码),然后将数据块粘贴为硬编码输出。

UNIQUE WRINKLE:我不想覆盖每次更新的数据。我希望它将 lower 粘贴到我的工作表上。

问题:我的VBA代码更新输入,但随后将每个更新的数据块粘贴到我的工作表上的相同位置。

这是我的代码。谢谢你的帮助!

更新:我仍然处于使用宏的粘贴功能的僵局,但已成功将其重写为嵌入式子例程,以避免其他提到的循环错误。我只是粘贴这里的粘贴子进行故障排除。请参阅ProcessData子:

NEW MACRO(PARTIAL):

Sub CheckRequestingData()
    ' Check if data has refreshed, if not, continue to wait
    Dim c As Range

    For Each c In Selection.Cells
        If c.Value = "#N/A Requesting Data..." Then
            Call Wait
            Exit Sub
        End If
    Next c

    Call ProcessData

End Sub

Sub ProcessData()

    Selection.Copy
    Range("B100").Select
                Selection.PasteSpecial Paste:=xlPasteValues
                Selection.PasteSpecial Paste:=xlPasteFormats
                Selection.Font.Color = vbBlue
    x = x + 1

    Call LoopStart

End Sub

OLD MACRO:

Sub LoopMacro()

Dim x As Integer
Dim y As Integer
Dim dataRange As Range: Set dataRange = Range("B35:LA54")
Dim mySheet As Worksheet: Set mySheet = ActiveSheet

'Loop through company tickers, inserting into Company Ticker cell
For x = 8 To 21
mySheet.Cells(2, 3).Value = mySheet.Cells(x, 2).Value

    For y = 1 To 14
        'Copy live data block with active company's data
        dataRange.Select
        Selection.Copy

        'Paste each company's data separately
        Range("B" & 35 + 21 * y).Select
            Selection.PasteSpecial Paste:=xlPasteValues
            Selection.PasteSpecial Paste:=xlPasteFormats
    Next

Next

End Sub

1 个答案:

答案 0 :(得分:0)

在子程序ProccessData中,您可以执行以下操作:

 Sub processData(byref datarange as range)

 Dim lastRow as integer
      lastRow = Sheets("SheetName").Cells(Rows.Count, 2).End(xlUp).Row

'if you have empty rows you can add++ to lastRow for every empty row you anticipate or want between data sets

dim index as string
      index = "B" & lastRow 

  datarange.Copy _ 
     destination:=Worksheets("SheetName").Range("index")
 end sub