Excel VBA 代码上的自动填充错误

Posted

技术标签:

【中文标题】Excel VBA 代码上的自动填充错误【英文标题】:Autofill error on Excel VBA code 【发布时间】:2017-02-03 02:27:09 【问题描述】:

尝试使用 VBA 自动填充功能(代码块结束),但每次尝试执行代码时都会遇到错误。我得到“范围类的自动填充方法失败”。有人可以帮我吗?谷歌搜索但没有任何效果。可能会忽略一些小东西。在此先感谢您的帮助。

Sub UpdateLAB() '---> still need to work on this

'author: css

Dim SalesBook As Workbook
Dim ws2 As Worksheet
Dim wspath As String
Dim n As Integer
Dim FirstRow As Long
Dim LastRow As Long
Dim LastRow2 As Long
Dim sourceCol As Integer
Dim RefCellValue2 As String
Dim ps As String
Dim Platts As Workbook


Application.Calculation = xlCalculationAutomatic

Set SalesBook = Workbooks("ALamb.xlsm")
Set ws2 = SalesBook.Worksheets("US LAB Price")
wspath = "C:\Users\scullycs\Desktop\P&O\Platts Data\Platts 2016.xlsm"

FirstRow = ws2.Range("B4").Row
LastRow = ws2.Range("B4").End(xlDown).Row + 1
LastRow2 = ws2.Range("c4").End(xlDown).Row
sourceCol = 2 'refers to the column your data is in

    For n = FirstRow To LastRow
    RefCellValue2 = Cells(n, sourceCol).Value

        If IsEmpty(RefCellValue2) Or RefCellValue2 = "" Then
        Cells(n, sourceCol).Offset(0, -1).Copy
        SalesBook.Worksheets("Control Page").Range("C8").PasteSpecial     (xlPasteValues)

        Else

     End If

Next n

        ps = SalesBook.Worksheets("Control Page").Range("C9").Text
        Set Platts = Workbooks.Open(wspath)
        Platts.Worksheets(ps).Activate
        Range("A13").End(xlDown).Select
        Selection.Offset(0, 11).Select

    If Selection.Value = "" Then
        MsgBox ("Platts data does not exist")
        Platts.Close

        Else
        Selection.Copy
        Set SalesBook = Workbooks("ALamb.xlsm")
        SalesBook.Worksheets("US LAB Price").Range("b1").End(xlDown).Offset(1, 0).PasteSpecial (xlPasteValues)
'this is where I get the error
        SalesBook.Worksheets("US LAB Price").Range("c4").AutoFill Destination:=Range("C4:C" & LastRow2), Type:=xlFillDefault

        Platts.Close

    End If

End Sub

【问题讨论】:

【参考方案1】:

很可能您的范围没有重叠或范围太大。如果您想参考,link。

    检查 LastRow2 的值。 确保填充范围来自同一张纸,以使它们重叠。为此,请将您的陈述分解为简单的步骤。稍后您可以合并。

建议将语句分解为

Set SourceRange = SalesBook.Worksheets("US LAB Price").Range("C4:C4")
Set fillRange = SalesBook.Worksheets("US LAB Price").Range("C4:C" & LastRow2)
SourceRange.AutoFill Destination:=fillRange, Type:=xlFillDefault

【讨论】:

以上是关于Excel VBA 代码上的自动填充错误的主要内容,如果未能解决你的问题,请参考以下文章

VBA Excel - 自动填充方法超出范围类错误

错误 1004:范围类的自动填充方法失败 vba excel 2010

VBA Excel 2010 - 自动填充不填充

Excel VBA 跨列自动填充

Excel VBA 自动填充目标

Excel VBA 自动填充问题