如何避免在进入列底部时使用选择和选择

时间:2019-03-05 14:48:03

标签: excel vba

我正试图停止使用ActiveCell等,因为StackOverflow已将其声明为“ nono”

我当前的代码是:

Sub SitesAndProd()

Set wb = ActiveWorkbook
Set ws = Worksheets("Data")
Set rng = ws.Cells(1, 13)

    LastRow = ws.Cells(Rows.Count, 1).End(xlUp).Row
    rng.FormulaR1C1 = "SitesAndProd"                                              'Rename Cell SitesAndProd

Set rng = ws.Cells(2, 13)

    rng.FormulaR1C1 = "=RC[-12]&RC[-4]"
    rng.Offset(0, -1).Select                                                     'Move left 1 column
    Selection.End(xlDown).Select                                                        'Go to bottom of column
    rng.Offset(0, 1).Select                                                      'Move right 1 column
    Range(Selection, Selection.End(xlUp)).Select                                        'Go to top of Column
    Selection.FillDown                                                                  'Copy Formula Down "Fill"

    Selection.Copy                                                                      'Ctrl + C
    Selection.PasteSpecial xlPasteValues                                                'Right click + V
    Application.CutCopyMode = False                                                     'Esc (stops the crawling ants


End Sub

以后使用Selection.End(xlDown).SelectxlUp时-它不会保存范围位置

确保范围保留在此处的最佳方法是什么?

使用以下内容时:

Range("M2").Select
ActiveCell.FormulaR1C1 = "=RC[-12]&RC[-4]"
Range("M2").Select
ActiveCell.Offset(0, -1).Select
Selection.End(xlDown).Select
ActiveCell.Offset(0, 1).Select
Range(Selection, Selection.End(xlUp)).Select
Selection.FillDown

该代码将提取正确的格式-从左1到底部,右1向上选择,然后向下复制

如果没有ActiveCellSelectionSelect的帮助,有人可以向我指出正确的方向吗?

2 个答案:

答案 0 :(得分:2)

这假设您在A列上计算的LastRow等于M列中的行数相同

Option Explicit
Sub SitesAndProd()

    Dim wb As Workbook, ws As Worksheet, LastRow As Long

    Set wb = ThisWorkbook
    Set ws = Worksheets("Data")
    ws.Cells(1, 13) = "SitesAndProd"
    LastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row

    With ws.Range(ws.Cells(2, 13), ws.Cells(LastRow, 13))
        .FormulaR1C1 = "=RC[-12]&RC[-4]"
        .Value = .Value
    End With

End Sub

我已经调整了一些代码。您需要声明变量wb As Workbookws As Worksheet。如果工作簿是您获得代码的地方,请使用ThisWorkbook代替ActiveWorkbook,您将获得更少的错误。

编辑:尽量避免使用全局变量。将它们作为变量传递给您的子对象或函数。

答案 1 :(得分:-1)

我希望您的代码是

Range("M2").Select
ActiveCell.FormulaR1C1 = "=RC[-12]&RC[-4]"
Range("M2").Select
ActiveCell.Offset(0, -1).Select
Selection.End(xlDown).Select
ActiveCell.Offset(0, 1).Select
Range(Selection, Selection.End(xlUp)).Select
Selection.FillDown

可以替换为:

Range(Range("M2"), Range("M" & ActiveSheet.Rows.Count).End(xlUp)).Formula = "=RC[-12]&RC[-4]"

如果您要用来确定最后一个填充单元格的列是Q列:

Range(Range("M2"), Range("Q" & ActiveSheet.Rows.Count).End(xlUp).Row).Formula = "=RC[-12]&RC[-4]"