首页 > 解决方案 > 如何在多个工作表上循环拖动公式

问题描述

我有一个包含大约 75 个工作表的工作簿,它们都包含每月更新的不同类型的数据。一些数据会自动更新,但几乎在每个工作表中,都有需要拖动的公式。我需要将每个工作表中的公式向下拖动 30 行。

所以我想遍历每个工作表,然后遍历包含要拖动的公式的每一列。我已经在列的第 1 行用字母“F”标记了要拖动的每一列,以便我可以放置一个 IF 语句来仅拖动这些列。

我现在的问题是我不知道如何选择包含公式的列的最后一个单元格,然后将其向下拖动 30 行。

Sub Drag_Formulas()

    'Number of Worksheets

        Dim i As Integer
        Dim ws_num As Integer
        ws_num = ThisWorkbook.Worksheets.Count

    'Number of columns

        Dim c As Integer

    'Loop 1

        For i = 1 To ws_num
            ThisWorkbook.Worksheets(i).Activate
                   For c = 1 To 105

                        If Cells(1, c).Value = "F" Then
                            Cells(20000, c).Select        'I used 20000 since no worksheet has data going as far as 20000, so that way I am sure to get the last cell with data
                            Selection.End(xlUp).Select
                            Selection.Copy

                        Else
                            Next c
                        End If

                    Next c

End Sub

所以我用一列的公式复制了最后一个单元格,但我不知道如何将它拖下 30 行,因为使用这段代码我不知道最后一个单元格在哪一行。

谢谢您的帮助!

标签: excelvba

解决方案


如前所述,目前宏实际上并没有做任何事情。但是,假设每列的公式在第 2 行,并且您想将其拖到该列的最后一行,您可以使用以下内容。

Sub drag()
Dim i As Long, col As Long, lastCol As Long, lastRow As Long
Dim copyRowAmt
Dim ws As Worksheet
Dim fmlaCell As Range

copyRowAmt = 30

For Each ws In ThisWorkbook.Worksheets
    With ws
        ' This assumes your column headers are in row 1,
        ' to get the total number of columns dynamically
        lastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
        For col = 1 To lastCol
            If .Cells(1, col).Value = "F" Then
                lastRow = .Cells(.Rows.Count, col).End(xlUp).Row
                .Range(.Cells(lastRow, col), .Cells(lastRow + copyRowAmt, col)).Formula = _
                    .Cells(lastRow, col).Formula
            End If
        Next col
    End With
Next ws
End Sub

请注意,这也避免使用.Select`.Activate`


推荐阅读