2017-06-30 154 views
0

簡單的任務,令人困惑的替代結果。Excel VBA日期複製不同,沒有明顯的原因?

我使用複製的數據範圍:

WS.Range("A2:Z" & lRow).Copy 
ThisWorkbook.Worksheets("Import").Range("A2:Z" & lRow).PasteSpecial xlPasteValues 

從複印紙的第一列是在格式12/05/2017 01:00:00一個日期(注意在日期和時間之間的雙空間)

在這個日期值的一個實例粘貼在罰款並作爲日期出來 - 太棒了!

在這個日期值的另一個實例粘貼,但出來作爲14/05/2017 01:00,這些不註冊爲日期,而是作爲文本字符串。

我注意到我可以通過單元格的日期和按回車轉換它們到日期,所以我嘗試使用.range("A1:A100").value = .range("A1:A100").value無濟於事。

我懷疑它可能與日月年的格式有關,而不是日月年(因爲它適用於從12月5日開始但不在14月5日開始的表) (1)可能會有另一個區別,(2)爲什麼按ENTER鍵工作正常,以及(3)我怎樣才能模仿按我的整個單元格範圍內的記憶(記住.value = .value不起作用)

+0

只是出於好奇,什麼都在你的電腦設置您的區域設置短/長日期? – Busse

+0

短日期設置爲dd/MM/yyyy,長日期設置爲dd MMMM yyyy – jamheadart

回答

1

簡而言之:類型轉換(首先在工作表上造成麻煩之前修復這些值)絕對是最好的選擇。

在長:

讓我們開始與這兩個值:

22.05.2017 12:00 
22.05.2017 12:00 

我會放在A1第一和第二的B1。請注意,Excel會經常嘗試進行類型轉換,因此在這種情況下,我會手動強制執行A1以通過格式化單元格來包含文本值。

我們來驗證:
enter image description here

使用立即窗口中,我們可以看到,編譯器可識別的A1內容作爲純文本價值,同時它承認在B1內容爲日期值。

您所需要的解決方案是確保任何文本值轉換爲日期值:

Option Base 1 

Sub pasteTextAsDate() 
    Dim dateArr As Variant 
    Dim rng As Range 

    Set rng = ThisWorkbook.Worksheets(1).Range("A1:A3") 

    ' In the line below, we fill the variant variable with the content of the range, casting the variable into an array of variants 
    dateArr = rng 

    ' For the sake of proving this code works, we'll start by printing the content and what type it is 
    For Each s In dateArr 
     Debug.Print s & " - " & TypeName(s) 
    Next s 

    For i = 1 To UBound(dateArr) 
     ' This is where we loop through the array and cast any string values to date values 
     dateArr(i, 1) = CDate(dateArr(i, 1)) 

     ' Here we verify for ourselves that the conversions are OK 
     Debug.Print dateArr(i, 1) & " - " & TypeName(dateArr(i, 1)) 
    Next i 

    ' And here we print the result to the worksheet 
    ThisWorkbook.Worksheets(1).Range("C1:C3").Value = dateArr 
End Sub 

結果:enter image description here

+0

感謝您提供這樣一個健康和簡潔的答案!我將在週末將其應用到我的工作表中,看看它是如何運行的,但這看起來很有希望。 – jamheadart

相關問題