2017-01-30 46 views
0

嗨我想創建一個宏,它有助於調整兩個時間序列。所以我必須讓這兩個時間序列具有相同的日期,假設如果沒有該日期的數據,則取前一天的價格。範圍副本VBA 400錯誤

我的所有代碼都可以工作,除了範圍拷貝部分。它不會將任何東西粘貼到插入的空白單元格中。有誰知道這是爲什麼?有問題的線是最後的Range線。我也嘗試了.Copy(Destination)方法,但它也沒有工作。錯誤處理程序說範圍類的副本失敗。

Sub Adjustdate() 

Dim lastrow As Long 
Dim n As Integer 
Dim read As Double 
Dim adju As Double 
Dim entry As Long 
Dim comp As Long 

lastrow = Cells(Rows.Count, "A").End(xlUp).Value 

n = 2 
While comp <> lastrow 
    entry = Cells(n, "A") 
    comp = Cells(n, "T") 
    read = Cells(n, "B") 
    adju = Cells(n, "C") 
    If (entry < comp) Then 
     Cells(n, "A").Insert Shift:=xlDown 
     Cells(n, "B").Insert Shift:=xlDown 
     Cells(n, "C").Insert Shift:=xlDown 
     Cells(n, "B") = read 
     Cells(n, "C") = adju 
     Cells(n, "A") = comp 
    End If 
    If (entry > comp) Then 
     Cells(n, "T").Insert Shift:=xlDown 
     Cells(n, "T") = entry 
     Cells(n, "T").Interior.ColorIndex = 8 
     Range(Cells(n, "U"), Cells(n, "AH")).Insert Shift:=xlDown 
     Range(Cells((n + 1), "U"), Cells((n + 1), "AH")) = (Range(Cells(n, "U"), Cells(n, "AH"))) 

    End If 
    n = n + 1 
Wend 

End Sub 

Screenshot of data 這裏的400錯誤後的代碼的截圖(它跑,直到它插入新行的一部分。)

+0

您的數據以升序排列?或者按降序排列? (可能會粘貼顯示前十行的截圖,主要是我們可以看到列A和列T中的內容。) – YowE3K

+0

您的「副本」正在複製行「n」中的值(剛剛設置爲空單元格通過前一行代碼,將現有值向下推一行)到行'n + 1'。您可能試圖將行'n - 1'複製到行'n'。 – YowE3K

+0

也許它與你的問題有關:在Range(Cells(n,「U」),Cells(n,「AH」))。Insert Shift:= xlDown'語句,從列U到AH的行'n' (Range(Cells(n,「U」)),Cells(n,「AH」)))指向空單元格,Range(單元格((n + 1) ),「U」),單元格((n + 1),「AH」))=(範圍(單元格(n,「U」),單元格(n,「AH」)))語句將複製空單元格值進入單元格中填充值爲'n'行的單元格 – user3598756

回答

0

根據您的屏幕截圖顯示的是你的數據在下降日期順序,你的問題造成的代碼如下兩行:

Range(Cells(n, "U"), Cells(n, "AH")).Insert Shift:=xlDown 
Range(Cells((n + 1), "U"), Cells((n + 1), "AH")) = (Range(Cells(n, "U"), Cells(n, "AH"))) 

的第一行上n行插入空細胞。然後第二行設置行n + 1(過去在第n行,直到您將它們向下移動的單元格)的單元格的值設置爲行n上的空單元格的值。

您需要正確的代碼是:

Range(Cells(n, "U"), Cells(n, "AH")).Insert Shift:=xlDown 
Range(Cells(n, "U"), Cells(n, "AH")) = Range(Cells(n + 1, "U"), Cells(n + 1, "AH")) 

您在您以前曾試圖以下命令評論說:

Range(Cells((n + 1), "U"), Cells((n + 1), "AH")).Copy _ 
           [Destination:=(Range(Cells(n, "U"), Cells(n, "AH")))] 

(我加了續行字符/只是爲了方便閱讀這篇文章)。

原因didn沒有工作是:

  1. 方括號([...])在這方面只是語法錯誤。

因此,讓我們放下方括號關,假裝你剛纔說

Range(Cells((n + 1), "U"), Cells((n + 1), "AH")).Copy _ 
            Destination:=(Range(Cells(n, "U"), Cells(n, "AH"))) 
  • 修訂後的命令說,複製的目的是要是(Range(Cells(n, "U"), Cells(n, "AH")))。雖然Range(Cells(n, "U"), Cells(n, "AH"))是一個有效範圍,但它周圍的圓括號((...))告訴VBA將其從對象指針轉換爲值。

    這意味着您的目的地將是Variant數組,它不是Range.Copy方法的有效「目標」。

  • 空投這些圓括弧會離開你的命令

    Range(Cells((n + 1), "U"), Cells((n + 1), "AH")).Copy _ 
                Destination:=Range(Cells(n, "U"), Cells(n, "AH")) 
    

    這將是一個有效的命令,做你想要的。

    下面是一個觀察窗口的顯示造成放置圓括弧一系列Range("A1:C1")變量類型的差異screendump:

    enter image description here

    總之......雖然它通常被認爲是一個很好的想法使用括號來增強代碼的可讀性(例如在一個複雜的公式中),不要在VBA中不需要的地方使用括號。