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

Excel VBA代码上的自动填充错误,excel,vba,Excel,Vba,尝试使用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 D

尝试使用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

最可能的情况是,您的范围没有重叠或范围太大。如果您想参考

  • 检查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