excel VBA -根据另一个选项卡上的数据将公式向下发送到数据的最后一行

gt0wga4j  于 2023-01-27  发布在  其他
关注(0)|答案(2)|浏览(232)

我正在尝试找出一种方法,根据第二个选项卡上有数据的单元格的数量,将公式发送到数据的最后一行,以捕获除标题之外的所有值。
我的公式位于Sheet1上的单元格A4:V4中。Sheet1上的第1:3行有标题。我尝试引用的单元格数位于Sheet2上。Sheet2上有88个包含数据的单元格,包括第1行的标题,因此有87个唯一值。我当前的操作方式只是将Sheet1上的公式向下发送到第88行。我不希望计数包括Sheet2第1行的标题。
它出现是因为Sheet2上有88个值,这是我在Sheet1上获得的总行数,包括我的3行标题,所以有85个唯一值。我应该在Sheet1上总共看到90行(包括现有标题),但不知道如何做到这一点。下面是我的公式:

Sub AmendRows()

Dim LastRow As String

Application.DisplayAlerts = False
Application.ScreenUpdating = False

Locktabs False

worksheet1.Select
LastRow = worksheet1.Range("A5").EntireRow.Select
rows(ActiveCell.row & ":" & rows.count).ClearContents
rows(ActiveCell.row & ":" & rows.count).ClearFormats

worksheet1.Range("A4:V4").AutoFill Destination:=worksheet1("A4:V" & worksheet2.range("A" & rows.count).end(xlUp).row)

Locktabs True

worksheetmain.Select
MsgBox "Rows Amended!"

End Sub

谢谢

kadbb459

kadbb4591#

Sub AmendRows()

    Dim worksheet1 As Worksheet, worksheet2 As Worksheet
    Dim n As Long, rng As Range
    
    Set worksheet1 = Sheet1 ' as appropriate
    Set worksheet2 = Sheet2 ' as appropriate
    
    n = worksheet2.UsedRange.Rows.Count - 1 ' no header
    If n < 1 Then Exit Sub
   
    With worksheet1

        With .Rows("5:" & .Rows.Count)
            .ClearContents
            .ClearFormats
        End With
        
        Set rng = .Range("A4:V4")
        rng.AutoFill Destination:=rng.Resize(n)
        
    End With
    MsgBox n & " Rows Amended! " & rng.Resize(n).Address

End Sub
nmpmafwu

nmpmafwu2#

向下复制公式

Option Explicit

Sub AmendRows()

    Const DST_FIRST_ROW As String = "A4:V4"
    Const SRC_FIRST_CELL As String = "A2"

    Application.ScreenUpdating = False
    'Application.DisplayAlerts = False ' ?
    
    Locktabs False
    
    Dim srCount As Long

    With worksheet2.Range(SRC_FIRST_CELL)
        Dim slCell As Range: Set slCell = .Resize(.Worksheet.Rows.Count - .Row _
            + 1).Find("*", , xlFormulas, , , xlPrevious)
        If Not slCell Is Nothing Then srCount = slCell.Row - .Row + 1
    End With
    
    With worksheet1.Range(DST_FIRST_ROW)
        With .Offset(1).Resize(.Worksheet.Rows.Count - .Row)
            .ClearContents
            .ClearFormats
        End With
        If srCount > 0 Then .Copy .Resize(srCount)
    End With
    
    Locktabs True
    
    If Not worksheetmain Is ActiveSheet Then
        With worksheetmain
            If Not .Parent Is ActiveWorkbook Then .Parent.Activate
            .Select
        End With
    End If

    'Application.DisplayAlerts = True ' ?
    Application.ScreenUpdating = True
    
    MsgBox "Rows Amended!", vbInformation

End Sub

相关问题