How to define variable in loop?

dmadhup

Board Regular
Joined
Feb 21, 2018
Messages
146
Office Version
  1. 365
I have defined variable like this:

Code:
Dim sumColumn15, sumColumn16, sumColumn17, sumColumn18, sumColumn19 As Long
sumColumn15 = 0
sumColumn16 = 0
sumColumn17 = 0
sumColumn18 = 0
sumColumn19 = 0

and I want to optimize this:

Code:
For i=15 To 19
  Dim sumColumn & i = 0
Next i

But no success. Any help please
 

Excel Facts

Why does 9 mean SUM in SUBTOTAL?
It is because Sum is the 9th alphabetically in Average, Count, CountA, Max, Min, Product, StDev.S, StDev.P, Sum, VAR.S, VAR.P.
I don't think you can do that.
And your original code does not even do what you think it does.

This:
Code:
Dim sumColumn15, sumColumn16, sumColumn17, sumColumn18, sumColumn19 As Long
declares sumColumn19 as Long, and the rest are declared as Variant.
Each variable needs to be declared explicitly like this:
Code:
Dim sumColumn15 As Long, sumColumn16 As Long, sumColumn17 As Long, sumColumn18 As Long, sumColumn19 As Long
or
Code:
Dim sumColumn15 As Long
Dim sumColumn16 As Long
Dim sumColumn17 As Long
Dim sumColumn18 As Long
Dim sumColumn19 As Long

What you are looking to do might require Arrays.
See: https://excelmacromastery.com/excel-vba-array/
 
Upvote 0
You could use an array like
Code:
   Dim sumColumn(15 To 19) As Long
As it's declared as long the values are automatically 0
 
Upvote 0
You can't do that. Also Dim doesn't go there, it's only used to declare variables.

As you have it written, use arrays.

Code:
Sub test()
Dim x As Long, sumColumn(15 To 19) As Long
For x = 15 To 19
    sumColumn(x) = 0
Next
End Sub

Although dimming a variable as Long will default it to 0 anyway.
 
Last edited:
Upvote 0

Forum statistics

Threads
1,214,832
Messages
6,121,841
Members
449,051
Latest member
excelquestion515

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top