Sub CreateTableD()
Dim WB As Workbook
Dim WS1 As Worksheet
Dim WS2 As Worksheet
Dim i As Long
Dim k As Long
'Dim n As Long
Set WB = Excel.ActiveWorkbook
Set WS1 = WB.Worksheets("List1")
Set WS2 = WB.Worksheets("List2")
i = 1
k = 1
'While Not IsEmpty(WS1.Cells(i, 1))
Do While WS1.Cells(i, 1).Value <> ""
If (WS1.Cells(i, 4).Value = "Depo" And WS1.Cells(i, 8).Value = "CZK") Then
WS2.Cells(k + 1, 4).Value = WS1.Cells(i, 7).Value
WS2.Cells(k + 2, 4).Value = WS1.Cells(i, 7).Value
WS2.Cells(k + 1, 7).Value = "79010000"
WS2.Cells(k + 2, 7).Value = "79010000"
ElseIf (WS1.Cells(i, 4).Value = "Loan" And WS1.Cells(i, 8).Value = "CZK") Then
WS2.Cells(k + 1, 4).Value = WS1.Cells(i, 7).Value
WS2.Cells(k + 2, 4).Value = WS1.Cells(i, 7).Value
WS2.Cells(k + 1, 7).Value = "75010000"
WS2.Cells(k + 2, 7).Value = "75010000"
k = k + 2
End If
i = i + 1
'Wend
Loop
Range("D1").Select
ActiveCell.FormulaR1C1 = "CZK"
End Sub
您好。我有一个代码,但它无法正常工作。如果满足两个条件,它必须返回另一个工作表上的兴趣以及一些静态数据(在代码中)我在第二张图片上显示了正确的结果。
答案 0 :(得分:0)
问题是你只是在贷款时增加k
。
If (WS1.Cells(i, 4).Value = "Depo" And WS1.Cells(i, 8).Value = "CZK") Then
ElseIf (WS1.Cells(i, 4).Value = "Loan" And WS1.Cells(i, 8).Value = "CZK") Then
k = k + 2
End If
当eith条件为True时递增k
将解决问题。
If (WS1.Cells(i, 4).Value = "Depo" And WS1.Cells(i, 8).Value = "CZK") Then
k = k + 2
ElseIf (WS1.Cells(i, 4).Value = "Loan" And WS1.Cells(i, 8).Value = "CZK") Then
k = k + 2
End If
我通常创建一个单独的函数来处理向表中添加数据。将代码分解为更小的单元有助于简化调试。
以下是我写它的方式。
Sub CreateTableD()
Dim x As Long
With Worksheets("List1")
For x = 2 To .Range("D" & .Rows.Count).End(xlUp).Row
If .Cells(x, 8).Value = "CZK" Then
If .Cells(x, 4).Value = "Depo" Then
AddList2Entry .Cells(x, 7).Value, "79010000"
AddList2Entry .Cells(x, 7).Value, "79010000"
ElseIf .Cells(x, 4).Value = "Loan" Then
AddList2Entry .Cells(x, 7).Value, "75010000"
AddList2Entry .Cells(x, 7).Value, "75010000"
End If
End If
Next
End With
End Sub
Sub AddList2Entry(interest As Double, StaticValue As Double)
Dim newRow As Long
With Worksheets("List2")
newRow = .Range("D" & .Rows.Count).End(xlUp).Row + 1
.Cells(newRow, "D").Value = interest
.Cells(newRow, "G").Value = StaticValue
End With
End Sub