wtorek, 27 października 2015

Excel: Iterate through x, return y's to table

My own humble attempts in VBA:

Enter one x and record 3 outputs:
Sub simulate()
    Dim x, xStart, xEnd, xStep As Single
    Dim i  As Integer


 With Worksheets("Simulate")
     
     i = 1
     xStart = .Range("f4").Value
     xEnd = .Range("g4").Value
     xStep = .Range("h4").Value
    
    
    .ListObjects("tblSim").DataBodyRange.Delete 'Shift:=xlToUp
    
    
    For x = xStart To xEnd Step xStep
        Worksheets("ProductList").Range("D10").Value = x
        With .Range("a1")
        .Offset(i, 0).Value = x
        .Offset(i, 1).Value = Worksheets("Analysis").Range("N19").Value
        .Offset(i, 2).Value = Worksheets("Analysis").Range("N20").Value
        .Offset(i, 3).Value = Worksheets("Analysis").Range("N21").Value
        End With
        i = i + 1
    Next x
    
End With
    
End Sub


Enter two variables and record one output, in a table suitable for a 3d plot (eg. heat map).

Sub simulate()
    Dim x, xStart, xEnd, xStep as Double
    Dim i, j  As Integer
    Dim y, yStart, yEnd, yStep as Double

On Error Resume Next
  
 With Worksheets("Simulate")
 
'Get iteration parameters

     xStart = .Range("h4").Value
     xEnd = .Range("i4").Value
     xStep = .Range("j4").Value
     
     yStart = .Range("h5").Value
     yEnd = .Range("i5").Value
     yStep = .Range("j5").Value
     
   'Clear old data
       '.ListObjects("tblSim").DataBodyRange.Delete 'Shift:=xlToUp
    .Range("A10:L100").ClearContents
     
'Generate x axis
    
    i = 1
    
    For x = xStart To xEnd Step xStep
            .Range("a20").Offset(0, i).Value = x
            i = i + 1
    Next x
    
'Get results
   
    j = 1
    For y = yStart To yEnd Step yStep
        .Range("a20").Offset(j, 0).Value = y
     
        i = 1
        
        Worksheets("ProductList").Range("D11").Value = y
        
        For x = xStart To xEnd Step xStep
            Worksheets("ProductList").Range("D10").Value = x
            .Range("a20").Offset(j, i).Value = Worksheets("ProductList").Range("N21").Value
            i = i + 1
        Next x
        
     j = j + 1
        
     Next y
     
  End With
    
End Sub


What about more dimensions? I think it would be the best occasion to feed an array in vba (then... how to save it?) or feed a cube in MS SQL. About saving/loading an array: http://stackoverflow.com/questions/18114527/load-multidimensional-vba-array-from-disk http://www.vb-helper.com/howto_read_write_binary_file.html

Brak komentarzy:

Prześlij komentarz