首页 > 解决方案 > 用另一个工作表中的数据动态填充下一个空行

问题描述

在此,我要感谢任何阅读本文的人花时间提出任何建议!我已经尝试了我在这里找到的其他示例,但它们似乎都不起作用,所以感谢您的任何建议!

所以基本上我有 3 张纸。在表 1 中,我将手动将数据输入到下一个空行(数据从 A 列到 U 列)。表 2 以某种方式链接到表 1,如果我选择一行并自动填充到下一行,它将显示表 1 中的数据(并且还会增加每个单元格中的值以解释通货膨胀)。

因此,基本上在我将数据输入到工作表 1 上的新行之后,我想运行一个宏,然后将工作表 2 上的最后一行动态自动填充到下一个空行。我还希望从表 2 到表 3 重复此操作。

一个例子是,如果工作表 1 和 2 都有数据到第 35 行,我希望能够在第 36 行手动输入数据,然后我的宏将自动填充工作表 2 上的第 35 到 36 行。

到目前为止我写的代码如下。解释一下,base/basee 和 home/homee 是我为比较 if/then 语句的特定列的值而命名的单元格。我在最后一行尝试使用 Offset(1,0) 自动填充到下一个单元格时不断收到错误 1004

Sub PracticeTool()

   Dim current1 As Integer
   Dim current2 As Integer

     Worksheets("City1").Select
     Application.Goto Reference:="base"
     Selection.End(xlDown).Select
     Selection.End(xlDown).Select

     current1 = Selection

     Worksheets("Inflation").Select
     Application.Goto Reference:="basee"
     Selection.End(xlDown).Select
     Selection.End(xlDown).Select

     current2 = Selection

If (current1 <> current2) Then

    Application.Goto Reference:="homee"
    Selection.End(xlDown).Select
    Selection.End(xlDown).Select
    Selection.End(xlDown).Select
    Range(Selection, Selection.End(xlToRight)).Select
    Selection.AutoFill Destination:=Selection.Offset(1, 0), Type:=xlFillDefault



End If

End Sub

表 1 示例数据:https ://i.stack.imgur.com/pTFo5.png

表 2 示例数据:https ://i.stack.imgur.com/kufrV.png

标签: excelvbadynamicautofill

解决方案


我没有得到你想要比较的确切内容,但我认为你很接近。

这段代码应该可以解决这个要求。

阅读评论并根据您的需要进行调整。

Public Sub AutoFillSheets()

    AutoFillRange "Sheet2", "A", "U"
    AutoFillRange "Sheet3", "A", "U"

End Sub


Private Sub AutoFillRange(ByVal targetSheetName As String, ByVal fromColumnLetter As String, toColumnLetter As String)

    Dim targetSheet As Worksheet
    Dim targetRange As Range

    Dim targetLastRow As Long

    Set targetSheet = ThisWorkbook.Worksheets(targetSheetName)

    ' Get the last row in source sheet
    targetLastRow = targetSheet.Cells(targetSheet.Rows.Count, 1).End(xlUp).Row

    ' Set the range to copy
    Set targetRange = targetSheet.Range(fromColumnLetter & targetLastRow & ":" & toColumnLetter & targetLastRow)

    ' You had the error in this line (below). Problem is that to use autofill you need to include the rows from which Excel would calculate the source range (see that I took the last row in the first column, and added one to the second column)
    targetRange.AutoFill Destination:=targetSheet.Range(fromColumnLetter & targetLastRow & ":" & toColumnLetter & targetLastRow + 1)

End Sub

推荐阅读