2017-08-17 101 views
0
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 

嗨。我有一个代码,但它不能正常工作。如果满足两个条件,它必须返回另一个工作表上的利息,还有一些静态数据(在代码中),我已经在第二张图片上显示了正确的结果。循环遍历worhsheet excel vba并在另一个工作表上返回数据

first worksheet with conditions

on this picture i showed what i need to get

+0

请写什么代码正在努力实现和它是如何工作没有一个具体的问题。它是否在特定的行中引发错误? – 0liveradam8

+0

我发布了第二张照片。它很容易理解我想要在图片上达成什么。代码没有任何错误,它的工作原理,但我认为它重写condiotion的第一部分,所以我只有结果列表 –

+0

第二个条件的数据,如果代码返回不正确的数据,那么它不起作用。这就像是说_my汽车工作,只是引擎不运行_ – jsotola

回答

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 

递增k当eith条件为真时将解决问题。

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 

enter image description here

+0

感谢您的解释!现在它工作! –

相关问题