Pedro Bernardos
Pedro Bernardos

Reputation: 67

How to implement an array with VBA Excel?

I have this code here, and I want to add an array with [12] (the 12 months).

The lines with // are the ones that I need to implement but I don't understand well how to do it!

The rest works fine :)

Sub titleHere()
Dim i As Long, var As Long
var = 0
//ARRAY[12] arr = {"Jan", "Fev", "Mar", etc...}

//Sheets("arr[0]").Cells(4, 3).Value = Sheets("INTRO").Cells(5, 2).Value
//For m = 1 To 11
    For i = 3 To 32
        If Cells(i, 19).Value = "C" Or Cells(i, 19).Value = "c" Then
            If Cells(i, 20) = 0 Then
                var = Sheets("INTRO").Cells(2, 2).Value
            Else
                var = Sheets("INTRO").Cells(2, 2).Value - Cells(i, 20).Value
          End If
        Else
            var = 0
        End If
//        Sheets("arr[m]").Cells(4, 3) = Sheets("arr[m]").Cells(4, 3) - var
        Next
//    Next
End Sub

Upvotes: 0

Views: 80

Answers (1)

VBasic2008
VBasic2008

Reputation: 54807

Loop Worksheets by Month

  • Not sure if I understood everything correctly, but with a few tweaks it should help you to get the job done.
  • Off course, change the months to the months in your language.

A Quick Fix

Option Explicit

Sub titleHere()
    
    Dim wb As Workbook
    Set wb = ThisWorkbook ' The workbook containing this code.
    
    Dim ws1 As Worksheet
    Set ws1 = wb.Worksheets("INTRO")
    Dim ws2 As Worksheet
    Set ws2 = wb.ActiveSheet ' ?
    
    Dim arr As Variant
    arr = Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", _
                "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
    
    Dim m As Long
    Dim i As Long
    Dim var As Long
    
    Dim ws As Worksheet
    Set ws = Worksheets(arr(LBound(arr)))
    ws.Cells(4, 3).Value = ws1.Cells(5, 2).Value
    
    For m = LBound(arr) + 1 To UBound(arr)
        Set ws = wb.Worksheets(arr(m))
        For i = 3 To 32
            If StrComp(ws2.Cells(i, 19).Value, "c", vbTextCompare) = 0 Then
                If ws2.Cells(i, 20) = 0 Then
                    var = ws1.Cells(2, 2).Value
                Else
                    var = ws1.Cells(2, 2).Value - ws2.Cells(i, 20).Value
                End If
            Else
                var = 0
            End If
                ws.Cells(4, 3) = ws.Cells(4, 3) - var
        Next i
    Next m

End Sub

Upvotes: 1

Related Questions