创建Excel宏以在可变/未知列数下复制公式?

时间:2013-01-14 21:19:21

标签: excel excel-vba formulas vba

我想在excel中创建一个我可以在其他工作表上重用的宏 从B4:B复制公式?到第X行。

我将把各行数据粘贴到几个不同工作表的A列中。我会在每张纸上都有一个按钮,我想标注“复制公式”。我编写了公式,将文本解析为3到250列,具体取决于工作表。我希望宏从B4突出显示到Selection.End(xlToRight)然后将该选择复制到A列中的最后一行数据。

我在想这样的事情,但我在第6行遇到了错误。

    Dim strCurrentSheet As String
    Dim LastRow As Integer
    Dim LastCol As Integer
    LastRow = Range("A4").End(xlDown).Row
    LastCol = Range("B4").End(xlToRight).Column
    Range(Cells(4, 2), Cells(4, LastCol)).AutoFill _ 
    Destination:=Range(Cells(5, 2), Cells(LastRow, LastColumn))

3 个答案:

答案 0 :(得分:1)

从一开始就考虑使用Excel表(Insert-> Table)来代替VBA宏 - 它具有或多或少的内置功能:

如果在表格中输入一个空列(或其旁边的相邻列),Excel将自动将公式应用于所有行。如果您在任何时候添加/复制数据,它将自动扩展表格,因此也会在所有列中应用公式!

答案 1 :(得分:0)

...我没有过多地测试这段代码,但这至少应该给你一个很好的起点并让你顺利开始:

Sub test()

  ' Get the last row and column on the sheet - store them in the variables
  Dim LastRow As Integer
  Dim LastCol As Integer
  LastRow = Range("A1").End(xlDown).Row
  LastCol = Range("B4").End(xlToRight).Column

  ' Copy cells B4:B[LastCol]  to  cells B4:[LastRow][LastCol]
  Range(Cells(2, 4), Cells(2, LastCol)).AutoFill _
         Destination:=Range(Cells(2, 4), Cells(LastRow, LastCol))

End Sub

希望有所帮助

答案 2 :(得分:0)

   Dim colABottom As Range
    Set colABottom = Range("A1").End(xlDown)

    Dim colEnd As Range
    Set colEnd = Range("A1").End(xlToRight)

    Dim lColStart As Long
    lColStart = 2
    Dim lColEnd As Long
    lColEnd = colEnd.Column

    Dim lRowStart As Long
    lRowStart = 1
    Dim lRowEnd As Long
    lRowEnd = colABottom.Row

    Dim startRange As Range
    Set startRange = Range("B1")

    Dim sourceRange As Range
    Set sourceRange = Range(startRange, startRange.End(xlToRight))

    Dim destinationFillRange As Range
    Set destinationFillRange = Range(Cells(lRowStart, lColStart), Cells(lRowEnd, lColEnd))

    sourceRange.AutoFill Destination:=destinationFillRange