[英]vba-excel: how to exclude copying a range of cells with for loop and if statement
我有以下代碼:
lr = Sheet1.Cells(Rows.Count, 1).End(xlUp).Row
For a = 1 To lr If (Sheet1.Cells(a, 1) = Date Or Date - 1) And (Sheet1.Cells(a, 2) = "AA" Or Sheet1.Cells(a, 2) = "BB" Or Sheet1.Cells(a, 2) = "CC") And Sheet1.Cells(a, 3) = array(0) Then Call ActivateSheet Sheet1.Range(Cells(a, 4), Cells(a, 10)).Copy Sheet2.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).PasteSpecial End If Next a
我有兩列包含數據。 在A列中,有DATE的值(我將其稱為currentDate)和DATE-1的值(將其稱為yesterDate) 。 在B列中,我可以具有三個不同的值,即AA , BB和CC 。 上面的我的if語句(我為代碼看起來不太合理而道歉,我仍在嘗試學習VBA。; P)基本上檢查A列中的值是currentDate還是yesterDate,並檢查B列中的值是AA , BB或CC 。 然后,如果列A和列B的值是給定值的任何組合,它將復制該單元格范圍並將其粘貼到Sheet2上 。
所以這就是我想要發生的事情。 從給定值的所有可能組合中,有一個我不想復制的組合,而該組合是yesterDate && CC 。
我只希望我的代碼復制yesterDate && AA , yesterDate && BB和currentDate && CC 。 根據用戶輸入,不太可能發生所有其他組合,例如currentDate && AA或currentDate && BB 。
我只想排除yesterDate && CC由我的代碼復制。 關於如何實現此目標的任何想法?
在這里,我給你一個。 試試這個。
Public Sub checkAndCopy()
Dim rowCount, row As Integer
Dim dateCell, valueCell, combinationCell As String
Dim isValid As Boolean
'Getting row count from Sheet1
rowCount = Sheet1.Cells(Rows.Count, 1).End(xlUp).row
'Looping all row from Sheet1.
For row = 1 To rowCount
'getting cell values
dateCell = Sheet1.Range("A" & row)
valueCell = Sheet1.Range("B" & row)
combinationCell = Sheet1.Range("C" & row)
'Sometime one of these cell should be blank or wrong date value.
'So, I added checking to avoid it.
'If these two cell are not empty, check date is valid or not.
If dateCell <> "" And valueCell <> "" Then
'If date value is valid, go on checking for copy cell.
If IsDate(dateCell) Then
'Reset isValid flag.
isValid = True
'You just want to exclude yesterday & CC.
'So, I only check for it.
If dateCell = Date - 1 And valueCell = "CC" Then
isValid = False
End If
'If both cell values are valid and also combination cell is valid, copy and paste cell.
If isValid And combinationCell = array(0) Then
'Select cells
Sheet1.Range(Cells(row, 4), Cells(row, 10)).Select
'Copy cells
Selection.Copy
'Paste cells
Sheet2.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).PasteSpecial
'Reset clipboard
Application.CutCopyMode = False
End If
End If
End If
Next row
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.