下面的代码执行但是:
For i = 2 To lRow
If .Range("A" & i).Value = rng1 Then
If .Range("C" & i).Value = rng2 Then
lastcell = .Range("B" & i).Value
End If
End If
Next i
似乎没有按照我的意图行事。我的意图是,如果细胞A&我的值=让我们说rng1,如果是真的那么继续下一个参数并检查我的C列单元格= rng2是否正确然后取那行我的B列和设置单元" C3"在证明选项卡上等于B&我的价值。然后继续前进到下一个i;如果它找到另一个符合上述两个条件的B,则将单元格c3.offset(1)=设置为该i的值。不幸的是,这对我不起作用。任何人都有任何建议:)
这是我运行代码时的样子:
Sub Extract_Bank_Amount()
Dim wb As Workbook
Dim ws As Worksheet
Dim rng1 As Range, rng2 As Range, lastcell As Range
Dim lRow As Long, i As Long
Set wb = ActiveWorkbook
Set ws = wb.Sheets("Bank Statement")
Set rng1 = wb.Sheets("Payroll Journal").Range("B1")
Set rng2 = wb.Sheets("Payroll Journal").Range("B3")
Set lastcell = wb.Sheets("Proof").Range("C3" & Rows.Count).End(xlUp).Offset(1)
wb.Sheets("Bank Statement").Activate
With ws
lRow = .Range("B" & .Rows.Count).End(xlUp).Row
For i = 2 To lRow
If .Range("A" & i).Value = rng1 Then
If .Range("C" & i).Value = rng2 Then
lastcell = .Range("B" & i).Value
End If
End If
Next i
End With
End Sub
答案 0 :(得分:2)
每次在列表末尾添加值时,都需要找到下一个空单元格。
Applies to
我会在" Payroll Journal"上给出范围。有意义的名字然后使用他们的定义名称来引用它们。
Sub Extract_Bank_Amount()
Dim wb As Workbook
Dim ws As Worksheet
Dim rng1 As Range, rng2 As Range, lastcell As Range
Dim lRow As Long, i As Long
Set wb = ActiveWorkbook
Set ws = wb.Sheets("Bank Statement")
Set rng1 = wb.Sheets("Payroll Journal").Range("B1")
Set rng2 = wb.Sheets("Payroll Journal").Range("B3")
wb.Sheets("Bank Statement").Activate
With ws
lRow = .Range("B" & .Rows.Count).End(xlUp).Row
For i = 2 To lRow
If .Range("A" & i).Value = rng1 Then
If .Range("C" & i).Value = rng2 Then
With wb.Sheets("Proof")
.Range("C" & .Rows.Count).End(xlUp).Offset(1).Value = .Range("B" & i).Value
End With
End If
End If
Next i
End With
End Sub
这将让你摆脱许多绒毛。
wb.Sheets("Payroll Journal").Range("B1").Name = "PayrollB1"
wb.Sheets("Payroll Journal").Range("B3").Name = "PayrollB3"
您还应该下载Rubberduck。 Rubberduck是VBA IDE的COM加载项,可帮助您调试和优化代码。对我来说最重要的是,通过为我格式化代码,我节省了大量时间。