代码之家  ›  专栏  ›  技术社区  ›  Lipis

如何使用VBA在Excel中自动填充单元格?

  •  4
  • Lipis  · 技术社区  · 16 年前

    我在第一列中有一些数据,后面有一些计算字段,我想用第一行中相同的规则自动填充其余的行。

    输入/计算数据的总行数和列数是已知的,我希望能为该数据提供一个工作示例:

      |  A  |  B  |    C   |    D   |      E     |
    ----------------------------------------------
    1 |  3  |  1  | =A1+B1 | =A1*B1 | =sum(C1:D1)|
    2 |  4  |  4  |        |        |            |
    3 |  5  | 23  |        |        |            |
    4 | 42  |  4  |        |        |            |
    5 |  7  |  4  |        |        |            |
    

    实际数据通常有10K+行和30+列。当我尝试手动操作时,有时会出现错误 Selection is too large . 我这样说是因为使用VBA的一般解决方案可能也不起作用,但是如果我知道如何自动填充这个示例,如果必要的话,我会按列进行。Excel的版本是2000,这不是我的错:)

    4 回复  |  直到 7 年前
        1
  •  6
  •   iDevlop    11 年前
    sub copydown()
        Range("c1:e" & Range("a" & activesheet.rows.count).End(xlUp).Row).FillDown
    end sub
    
        2
  •  1
  •   d..    16 年前

    基本的,但它应该给你一些东西来建立,它在Excel2003中工作(我有最老的)。

    Option Explicit
    
    Public Sub CopyFormulaeExample()
    
        On Error GoTo Handle_Exception
    
        Dim lastRow As Long
        Dim wrkSheet As Excel.Worksheet
    
        'Book and sheet names hard-coded for this example
        Set wrkSheet = Application.Workbooks("Book1").Worksheets("Sheet1")
    
        'Get the index of the last row used
        lastRow = wrkSheet.UsedRange.End(xlDown).Row
    
        'Copy the cells containing the formulae; also hard-coded for this example
        Range("C1:E1").Select
        Selection.Copy
        'Paste the selection to the range of interest
        Range("C2:E" + CStr(lastRow)).PasteSpecial xlPasteAll
    
        'Alternative approach
        Range("C1:E1").Copy Range("C2:E" + CStr(lastRow))
    
        'Release memory and exit method
        Set wrkSheet = Nothing
        Exit Sub
    
    Handle_Exception:
    
        Set wrkSheet = Nothing
        MsgBox "An error has been found: " + Err.Description
    
    End Sub
    
        3
  •  1
  •   Curtis Patrick    16 年前

    使用向下复制(ctrl-D)功能。

    选择单元格c1-e1,然后一直向下(如果有10000行数据,则所选单元格范围为c1-e10000)。

    这会将单元格内容(公式)复制到它下面的所有单元格。

    http://www.google.com/search?q=using+excel+ctrl-d

        4
  •  -2
  •   lprsd    16 年前

    以下是我是如何做到的,当我做到的时候:)

    Ctrl+C
    <--
    Ctrl+Shift+Down
    -->
    Ctrl+Shift+Up
    Ctrl+V
    

    在我看来,这是最有效的方法。没有什么可以阻止您将其包装到宏中并指定一个方便的键绑定。

    推荐文章