Excel/VBA Solution

Advertisement


Question
Hi Tom,
I have a loop that assigns values to variables. What must I write to name the variable while in the loop?

For example:

Static name0 As String
Static name1 As String
Static name2 As String

For i = 0 to 2

If Range("C5").Offset(i,0).Value = 1 Then

<<<Here is where I would name the variable depending on the value of i >>>>>

ex: "name" & i = "Message"

I need to add the value of i to the string "name" to assign the value to the already declared variable..

Thanks for the help,
Jesse

Answer
Jesse,

excel doesn't support what you describe as you describe it.  I will show you a workaround.  Then I will show you an approach that demonstrates how VBA is designed to do something similar to what you want.

If you want to go with separate variables, then you would have to use a case statement (or if statements) as shown below

Static name0 As String
Static name1 As String
Static name2 As String

For i = 0 to 2

If Range("C5").Offset(i,0).Value = 1 Then
Select Case i
  Case 0
    name0 = "message0"
  Case 1
    name1 = "message1"
  Case 2
    name2 = "message2"
end select
end if


If I was going to need to do this I would create an array

dim name(0 to 2) as String

For i = 0 to 2

If Range("C5").Offset(i,0).Value = 1 Then

<<<Here is where I would name the variable depending on the value of i >>>>>

  name(i) = "Message"




then later you would do something like

msgbox name(2)

or
i = 2
msgbox name(i)

--
Regards,
Tom Ogilvy  
About Excel
This topic answers questions related to Microsoft Excel spreadsheet (or workbook) stand-alone or Mircrosoft Office Excel including Excel 2003, Excel 2007, Office 2000, and Office XP. You can get Excel help on Excel formulas(or functions), Excell macros, charting in Excel, advanced features, and the general use of Excel. This does not provide a general Excel tutorial nor the basics of using a spreadsheet. It provides specific answers to using Microsoft Excel only. If you do not see your Excel question answered in this area then please ask an Excel question here

Excel

All Answers


Answers by Expert:


Ask Experts

Volunteer


Tom Ogilvy

Expertise

Selected as an Excel MVP by Microsoft since 1999. Answering Excel questions in Allexperts since its inception in 2001. Able to answer questions on almost all aspects of Excel's internal capabilities. If seeking a VBA solution, please specify that in your question itself so I give you the answer you want. [Excel has weak protection - if you are distributing an application, I don't answer questions on how to protect your project from your users.]

Experience

Extensive experience.

Education/Credentials
Master of Science (MS) degree Operations Research (ORSA)

Awards and Honors
Microsoft MVP in Excel.

©2016 About.com. All rights reserved.