2017-02-03 57 views
0

嘗試使用VBA自動填充功能(代碼塊結束),但每次嘗試執行代碼時都會遇到錯誤。我得到「範圍類的自動填充方法失敗」。有人能幫助我嗎?搜索谷歌,但沒有任何作品。大概可以忽略一些小事。先謝謝您的幫助。Excel 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

  1. 檢查LastRow2的值。
  2. 確保填充範圍來自同一張紙上,以使它們重疊。爲此,請將您的陳述分成簡單的步驟。以後你可以合併。

會建議語句分解成

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 
+0

感謝您的反饋,現在這個完美的作品。 –