创build一个Excelmacros以跨variables/未知数量的列向下复制公式?

我想在Excel中创build一个macros,我可以在其他工作表上复制从B4:B下来的公式。 到行号X.

我将粘贴各行数据到几个不同工作表的A列。 每张表格上都会有一个button,我想标记“复制公式”。 我已经写了公式parsing出来的文本到3到250列的任何地方,根据表。 我想macros从B4突出显示Selection.End(xlToRight)然后复制该select,直到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)) 

而不是一个VBAmacros这样做,考虑从一开始就使用Excel表格(插入 – >表格) – 它有或多或less的内置function:

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

…我没有太多的testing这个代码,但是这至less应该给你一个很好的起点,

 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 

希望能帮助到你

  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