【问题标题】:Dynamically fill the next empty row with data from another sheet用另一个工作表中的数据动态填充下一个空行
【发布时间】:2020-05-06 19:44:21
【问题描述】:

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

所以基本上我有 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

【问题讨论】:

  • 请发布一些示例数据
  • @RicardoDiaz 刚刚添加了两个例子!
  • 你会按下按钮来复制单元格还是什么事件会触发它?
  • @RicardoDiaz 是的,我计划将宏分配给一个按钮,该按钮将触发工作表 2 上的自动填充
  • 我不明白你的代码你在比较什么?这些命名范围中有 2 个数字?

标签: excel vba dynamic autofill


【解决方案1】:

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-07
    • 1970-01-01
    • 1970-01-01
    • 2023-01-14
    • 2015-08-19
    • 2016-05-15
    • 2020-05-25
    • 1970-01-01
    相关资源
    最近更新 更多