不确定发生了什么,但是我无法获得一个简单的For If循环来在VBA中完全发挥作用。以下代码仅粘贴AH =“ Changed”的第一个实例,而不粘贴范围中的其他实例。有什么想法吗?
Dim x As Integer ' Defining variables to be used
Dim b As Integer
Dim ClaimsDB As Integer
ClaimsDB = Evaluate("CountA(B18:B28)") 'Counting how many rows in the specified range are empty, in order to only run the loop a specified amount of times
'Copy data that has been marked "changed" in a previous worksheet to a different worksheet
For b = 1 To ClaimsDB
If Range("AH" & b + 17).Value = "Changed" Then 'AH(b+17) is marked "Change" if a change has been made - I only want the rows with "Changed" in AH to be copied
x = Sheets("Change register").Range("B" & b + 17).Value 'Define x as equal to the value in column B, row b+17, for a row with AH = "Changed"
'Copy row with AH = "Changed" from E:AF
Sheets("Change register").Range("E" & b + 17).Select
Range(Selection, Range("AF" & b + 17)).Select
Selection.Copy
'Switch worksheets to product data, and paste the selection in a row corresponding to x+12, starting in column D
Sheets("Product data").Select
Sheets("Product data").Cells((x + 12), 4).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
End If
Next b ' Repeat the loop for the next value of b, until ClaimsDB has been reached
答案 0 :(得分:0)
尝试以下操作:
Option Explicit
Sub CopyChangedRows()
'Integer is stored as Long anyway, so it is better to use Long
'also i is usually used as iterator variable :)
Dim x As Long, i As Long, ws1 As Worksheet, ws2 As Worksheet
'always hold references to your sheets (when using multiple sheeets) in variable to keep code clean
Set ws1 = Sheets("Change register")
Set ws2 = Sheets("Product data")
'Copy data that has been marked "changed" in a previous worksheet to a different worksheet
For i = 18 To 28
'loop will skip empty cells, as they value will be different from "Changed"
If ws1.Range("AH" & i).Value = "Changed" Then
x = ws1.Range("B" & i).Value
'Copy row with AH = "Changed" from E:AF
ws1.Range(ws1.Range("E" & i), ws1.Range("AF" & i)).Copy
'Switch worksheets to product data, and paste the selection in a row corresponding to x+12, starting in column D
'whole copied range will be pasted starting in specified range
ws2.Range("D" & x + 12).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
End If
Next
End Sub