首页 文章

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

提问于
浏览
2

我想在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

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

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

  • 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
    

    希望能帮助到你

  • 1
    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
    

相关问题