复制在宏

时间:2017-02-09 14:30:57

标签: excel vba excel-vba

我是VBA初学者,因此,以下查询对您来说可能很容易,但我无法做到

我想要的是以下内容:

使用

构建宏
  1. 在一张(现有)和
  2. 上输入日期和信用评级
  3. 将其复制并粘贴到预定义的表格中
  4. 每当您在输入字段中输入新数据并单击宏按钮时,宏应该将其复制并再次粘贴到表中,但在最后一个单元格/行下面使用两行。
  5. 有一个图表读取范围的数据,数据被粘贴到该范围,并自动将其范围调整为新粘贴的值。
  6. 我希望,我已经足够好地解释了我的问题,以便你可以提供帮助。

    Dim x As Integer 
    Worksheets("Input").Range("D6:D7").Copy 
    x = 2 
    Do 
      x = x + 2 
      Worksheets("Chart").Range("B" & x).PasteSpecial Paste:=xlPasteValues,Transpose:=True, xlPasteValues 
    Loop Until x = 56 
    Application.CutCopyMode = False 
    End Sub
    

    谢谢!

2 个答案:

答案 0 :(得分:0)

尝试以下代码:

Option Explicit

Sub CopyTowRowsbelow()

Dim x As Long

Worksheets("Input").Range("D6:D7").Copy

With Worksheets("Chart")
    x = .Cells(.Rows.Count, "B").End(xlUp).Row ' find last row in column B
    .Range("B" & x + 2).PasteSpecial Paste:=xlPasteValues, Transpose:=True ' Paste the value 2 rows below the last cel with data
End With
Application.CutCopyMode = False

End Sub

答案 1 :(得分:0)

我发现复制粘贴通常是一种不好的做法,因为它使用系统剪贴板并且可以删除用户在剪贴板中的数据。相反,我尝试显式设置目标值。如果将其粘贴到输入表的代码模块中,则此代码应该有效。

Public Sub Worksheet_Change(ByVal Target As Range)
'this built in subroutine in excel executes whenever something is changed on the worksheet
'we'll use this subroutine to determine range "D6:D7" was part of the sheet that was changed

'declare the range we want to detect if a change occurred, we'll just monitor range D7
Dim rangeMonitorForChange As Range
Set rangeMonitorForChange = Worksheets("Input").Range("D7")

'if the range changed on the sheet and the range were monitoring overlap/intersect then we'll call the method to upadte the chart sheet
  If Not Application.Intersect(Target, rangeMonitorForChange) Is Nothing Then
      copyDown
  End If
End Sub


Sub copyDown()
'define where to "copy" from
Dim rngSource As Range
Set rngSource = Worksheets("Input").Range("D6:D7")

'find the row we're going to "paste" to
Dim destRow As Long
destRow = Sheets("Chart").Range("B" & Sheets("Chart").Rows.Count).End(xlUp).Row + 2

'define "paste" destination
Dim rngDest As Range
Set rngDest = Sheets("Chart").Range("B" & destRow & ":B" & destRow + 1)

'"paste" the values in
rngDest.Value = rngSource.Value

End Sub