![](/img/trans.png)
[英]Copying the cell value preserving the formatting from one cell to another in excel using VBA
[英]Formatting a cell value to “MMMM” using excel vba
我有以下代碼,需要一些幫助進行修改。
Sub CopyDataBasedOnTimeRangeMonth()
Dim i, LastRow
Dim Cell As Range
LastRow = Sheets("OPA").Range("A" & Rows.Count).End(xlUp).Row
Sheets("Sheet2").Range("A3:U500").ClearContents
For i = 2 To LastRow
If Sheets("OPA").Cells(i, "G").Value >= Range("U1") And Sheets("OPA").Cells(i, "G").Value < Range("AC1") Then
Sheets("OPA").Cells(i, "R").EntireRow.Copy Destination:=Sheets("Sheet2").Range("A" & Rows.Count).End(xlUp).Offset(1)
End If
Next i
End Sub
對於“ G”的計算,我要使用要計算的值的“ MMMM”格式。 在一個excel公式中,我可以使用諸如Text(“ G12”,“ MMMM”)之類的內容,然后繼續使用該公式,但是我不知道如何修改about代碼以僅使用Month only值“ G”。
在此先感謝您提供的任何幫助。
最好也將[U1]作為日期,然后將其格式化為月
If Month(Sheets("OPA").Cells(i, "G")) >= Month(Range("U1"))
您可以在下面看到代碼的變體,該變體已使用Davesexcel
(+1)提供的變體進行了更新,並且在我這一邊也做了一些更正,以簡化可讀性:
1)將對Range()
)的絕對引用替換為[]
速記方法;
2)刪除了Destination:=
過多,目標范圍也被行替換,因為當您復制行時,目標應為該行;
3)應用with (object)
方法;
4)添加變量的類型,例如, i
替換為i&
(表示i as long
)
Sub CopyDataBasedOnTimeRangeMonth()
Dim i&, LastRow&, Cl As Range
LastRow = Sheets("OPA").Range("A" & Rows.Count).End(xlUp).Row
Sheets("Sheet2").[A3:U500].ClearContents
With Sheets("OPA")
For i = 2 To LastRow
If Month(.Cells(i, "G")) >= Month(.[U1]) And _
Month(.Cells(i, "G")) < Month(.[AC1]) Then
.Rows(i).Copy Sheets("Sheet2").Rows(Sheets("Sheet2").Range("A" & Rows.Count).End(xlUp).Row + 1)
End If
Next i
End With
End Sub
經過測試,工作正常。
資源:
目的地:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.