编辑录制的宏的代码

时间:2018-06-13 19:57:01

标签: excel vba excel-vba

我是使用宏和代码的新手,我遇到了一个小问题。我有一张表格,我在一行中更新值。由于这些更新是进程的一部分,我希望excel将我的行记录为工作簿中下一页中的一种历史记录。我录制了一个宏,当我按下cntrl + r时,它会从我的数据表中复制第一行,在历史页面上插入一行,然后将数据复制到该新行上。唯一的问题是我的数据表将有多行数据,我希望宏复制我选择的行,而不是每次都复制第一行。我把代码放在下面。

谢谢!

Sub RecordTracker()
RecordTracker Macro
Records the updated row as a history row in Documentation Sheet
Keyboard Shortcut: Ctrl+r

    Sheets("Documentation").Select
    Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
    Sheets("Tracker").Select
    Range("A3:S3").Select
    Selection.Copy
    Sheets("Documentation").Select
    Range("A1").Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False
End Sub

很抱歉,如果我的代码格式有点偏差。第一篇文章!

3 个答案:

答案 0 :(得分:1)

在第一个.Select之前添加此行:

r = ActiveCell.Row

然后你想改变这一行:

Range("A3:S3").Select

到此:

Range("A" & Cstr(r) & ":S" & Cstr(r)).Select

我认为应该这样做。

注意:使用.Select速度很慢并且存在其他一些可靠性/交互问题,因此我们通常会建议不要这样做。但是,如果没有它就很难进行真正的复制操作,因此在这种情况下可能没问题。 然而,如果你不真的需要一个真正的副本(格式,公式,等等),但只想要值,那么有一个更好的方法做此

这是一种更好的方法,因为您只需要数据。我把它分成了各行,以便你可以看到它是如何完成的。

Sub RecordTracker()
'RecordTracker Macro
'Records the updated row as a history row in Documentation Sheet
'Keyboard Shortcut: Ctrl r

    ' get the worksheet objects
    Dim wsDoc As Worksheet, wsTrak As Worksheet
    Set wsDoc = Sheets("Documentation")
    Set wsTrak = Sheets("Tracker")

    ' get the source (current) row
    Dim r As Long
    r = ActiveCell.Row

    'Make the output row
    wsDoc.Range("A2").EntireRow.Insert shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove '.Range("A2:S2").Select

    ' get the source data
    Dim dat() As Variant
    dat = wsTrak.Range("A" & CStr(r) & ":S" & CStr(r))

    ' set the output range
    Dim outRng As Range
    Set outRng = wsDoc.Range("A2:S2")

    ' copy data to the output range
    outRng = dat
End Sub

答案 1 :(得分:1)

  1. 将在(Documentation
  2. 的工作表A2上插入新行
  3. 复制您选择的行(来自工作表Tracker,范围A:S
  4. 将值粘贴到Documentation A2(这是您新创建的行)
  5. 这需要粘贴在工作表Tracker上的VBE中以执行

    请注意,通过避免使用.Select方法,可以大大减少代码(就行而言)。您可以找到一些有用的信息here

    Sub StoreChanges()
    
        Sheets("Documentation").Range("A2").EntireRow.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
        Sheets("Tracker").Range(Cells(ActiveCell.Row, "A"), Cells(ActiveCell.Row, "S")).Copy
        Sheets("Documentation").Range("A1").PasteSpecial Paste:=xlPasteValues
    
    End Sub
    

答案 2 :(得分:0)

我假设在数据表(追踪器)中您希望粘贴选定的范围/行而不仅仅是第三行A3:S3

  

我录制了一个宏,当我按下cntrl + r时,它会从我的数据表中复制第一行,在一行上插入一行   历史记录页面,然后将数据复制到该新行

尝试删除Range("A3:S3").Select代码行。现在,当您手动选择工作表跟踪器中的一行时,该行应在代码中使用Selection.Copy

Sheets("Documentation").Select
Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Sheets("Tracker").Select
## removed Range("a3:s3").select
Selection.Copy
Sheets("Documentation").Select

如果您想在第二行添加新行,只需在代码Sheets("Documentation").Rows("2:2").Select之前添加Selection.Insert

相关问题