Is is possible to use a simple variable name to refer to a location in a VBA array - excel

Is is possible to use a simple variable name to refer to a location in a VBA array?
I thought the location might be an object so I tried doing it kind of like this:
Sub ArrayRef()
Dim X As Integer
Dim ArrayWithQuiteALongName(1 To 3) As Integer
Dim A As Object
For X = 1 To 3
Set A = ArrayWithQuiteALongName(X)
A = X * 10
A = A * 10
Next X
Debug.Print ArrayWithQuiteALongName(1) = 100
Debug.Print ArrayWithQuiteALongName(2) = 200
Debug.Print ArrayWithQuiteALongName(3) = 300
End Sub
In the example I would expect a Debug.Print output of
TRUE
TRUE
TRUE
But this doesn't work and I can't seem to find any information on if it's possible

Related

Getting an Invalid Qualifier error. I am trying to print the common brands from a workbook to another with help of an array

The code when run shows no error but no values are being printed:
Sub HouseOfCommons()
Dim filePath As String
filePath = "D:\"
Dim Brands(100) As String
Dim QuesRange(4) As String
QuesRange(0) = "A10:F125"
QuesRange(1) = "A137:F254"
QuesRange(2) = "A266:F307"
QuesRange(3) = "A319:F362"
QuesRange(4) = "A373: F415"
Dim inputx As String
inputx = InputBox("Enter the brand")
For I = 0 To 4
Workbooks.Open (filePath + "JP_CP_2019Q3_Data Tables.xlsx")
ActiveWorkbook.Worksheets("P_2_3w").Select
If (Workbooks("JP_CP_2019Q3_Data Tables.xlsx").Worksheets("P_2_3w").Range("A137:A500").Find(inputx)) = True Then
If (Brands.Contains(inputx)) = False Then
Brands.Add (inputx)
For x = 1 To UBound(Brands)
Workbooks.Open ("D:\InProcess.xlsm")
ThisWorkbook.Sheets("Sheet2").Cells.Value(I, 1) = inputx
Next x
End If
End If
Next I
End Sub
The code should store the common brands into an array and print them in a separate workbook called "InProcess.xlsm"
You're using .NET syntax which is not supported in VBA:
If (Brands.Contains(inputx)) = False Then
possible replacement:
If IsError(Application.Match(inputx, Brands, 0)) Then
Your code seems to have other problems but without knowing what it's supposed to do it's difficult to offer suggested fixes.

Setting variable values dynamically using VBA

I dont work with VBA much, I have a number of global integer variables, such as DFromRow1, DFromRow2, DFromRow3 up until DFromRow20. I want to set each of these in sequential order in this manner(This is just a very simple example to help you understand what I am trying to do) :
Dim Count as integer
Count = 0
Begin Loop(loop here for 20 times)
Count = Count + 1
DFromRow & Count = Count
End Loop
The idea here is that the global variables will be populated as such:
DFromRow1 = 1
DFromRow2 = 2
DFromRow3 = 3
... up until 20
However I get an error on the & :
Expected: expression
Is there a way to do this or am I being too ambitious with what I want ?
Thanks appreciate any help.
Instead of declaring 20 variables DFromRow you can use array
Something like this
Option Explicit
Public ArrDFromRow(20)
Sub Test()
Dim i As Long
For i = 1 To 20
ArrDFromRow(i) = i
Next i
For i = 1 To 20
Debug.Print ArrDFromRow(i)
Next i
End Sub
You can use an Array to store your values like this:
Dim DRowArray(1 to 20) as Long
Sub PopulateDFromRowArray()
Dim i as Integer
For i = LBound(DRowArray) to UBound(DRowArray)
DRowArray(i) = i
Next
End Sub
Or a Dictionary, albeit you need to set a VBA reference to Microsoft Scripting Runtime:
Dim DRowDict as Scripting.Dictionary
Sub PopulateDFromRowDictionary()
Dim i as Integer
Set DRowDict = New Scripting.Dictionary
For i = 1 To 20
DRowDict.Add "DFromRow" & i, i
Next
End Sub

Syntax for incrementing not giving expected outcome

I am currently writing a macro for excel and experiencing some issues using the "i = i + 1" code. I have used this elsewhere in my macro and it has worked fine, however for this section it is failing to increment correctly.
As this is quite a large piece of code, I have only included the section which is having issues, however if in order to properly debug this more code is required i am happy to provide this.
I have checked the syntax as has a colleague and we are struggling to find out where the issue is originating from, any help on this would be appreciated.
All declared variables:
D
im lastSite As Range: Set lastSite = wsReport.Range("I2:I1000")
Dim expectedSite As Range: Set expectedSite = wsReport.Range("H2:H1000")
Dim expectedLocation As Range: Set expectedLocation = wsReport.Range("G2:G1000")
Dim lostTOA As Range: Set lostTOA = wsTOAOut.Range("G2:G1000")
Dim lostMissing As Range: Set lostMissing = wsMissing.Range("G2:G1000")
siteCode = wsHome.Range("Q6")
Dim last
Dim expected
Dim lostOut
Dim lostMiss
departments = wsHome.Range("R6:R20")
Working as intended:
Dim iAllocation As Integer
For Each dept In departments
If dept = "" Then
Exit For
End If
wsLBD.Range("A" & rowCounterDepartments).Value = dept
For Each expected In expectedLocation
If expected = dept And Not expected = "" Then
iAllocation = iAllocation + 1
End If
Next
wsLBD.Range("C" & rowCounterDepartments).Value = iAllocation
iAllocation = 0
rowCounterDepartments = rowCounterDepartments + 1
Next
Not Working as intended:
rowCounterDepartments = 2
departmentsOut = wsHome.Range("R6:R20")
Dim iLoss As Integer
Dim iMissing As Integer
For Each lostOut In lostTOA
If lostOut = "" Then
Exit For
End If
For Each deptOut In departmentsOut
If lostOut = deptOut And Not lostOut = "" Then
iLoss = iLoss + 1
End If
Next
wsLBD.Range("B" & rowCounterDepartments).Value = iLoss
iLoss = 0
rowCounterDepartments = rowCounterDepartments + 1
Next
The output expected should be a total count for each department, however it is only outputting a 1 or 0 per line
This has now been resolved, i re-wrote this piece of code and it was a syntax error on my part, a couple of the pieces were the wrong way round.

Goal seek Run-time 1004 error when using application.run from another Workbook

I have a run-time error that I can't solve despite having searched deeply into many forum.
Here is the problem: I am using a Macro in a Model looking for a optimal allocation through a Goal-Seek function.
When I use it within that model (let's call it Model 1), the macro works perfectly.
However, i need to work in that model and in another one, to get data that will fill a table located in a 3rd excel file, which is then my "main file" (let's call it Model 3).
Thus, I need to call that macro located in Model 1 via an Application.run from Model 3.
And when I do so, I get a "Run-time error '1004': Reference isn't valid." which relates to the Goal-seek function that I use in Model 1.
Furthermore, if after that I come back to Model 1 and try to use the macro, I get the exact same error message while it was working before.
Here are my codes:
Model 3 (main):
Sub Test_Optim()
Dim JFMPath As String
Dim MacroPath As String
JFMPath = Sheets("Inputs").Range("D2")
MacroPath = Sheets("Inputs").Range("A3")
Workbooks.Open JFMPath
Application.Run (MacroPath)
End Sub
Model 1:
Option Explicit
Option Base 1
Sub Optimization_Alloc()
'Definitions
Dim i As Integer
Dim k As Integer
Dim IRR As Single
Dim IRRDelta As Single
Dim vIRR() As Single
Dim MinIRR As Single
Dim vPPA() As Single
Dim PPALevel As Single
Dim MinPPA As Single
Dim Position As Integer
Dim FlipYearIterations As Integer
Dim IterTF As Boolean
Dim IterStep As Single
Dim FlipYear As Integer
Dim OptFlipYear As Integer
Dim vFlipYear() As Integer
Dim xDistribution As Single
Dim OptxDistribution As Single
Dim vXDistribution() As Single
'enables goal-seek iterations, MaxIterations is the number you would wanna change
IterTF = Application.Iteration = True
IterStep = Application.MaxIterations
With Application
.Iteration = True
.MaxIterations = 500
.MaxChange = 0.0001
End With
FlipYearIterations = 10
ReDim vPPA(FlipYearIterations) As Single
ReDim vFlipYear(FlipYearIterations) As Integer
ReDim vXDistribution(FlipYearIterations) As Single
ReDim vIRR(FlipYearIterations) As Single
For i = 1 To FlipYearIterations
vFlipYear(i) = 2027 + i - 1
Next i
'Loops through different FlipYears. For every year, optimal allocation of cash/tax is calculated by goalseek.
For k = 1 To FlipYearIterations
Worksheets("As_Yr").Cells(345, 9) = vFlipYear(k) 'Optimal flip year
Worksheets("As_Yr").Cells(350, 9).GoalSeek Goal:=0, ChangingCell:=Worksheets("As_Yr").Cells(346, 9)
'Here is the Goalseek function from which I get the run-time error
xDistribution = Worksheets("As_Yr").Cells(346, 9)
PPALevel = Worksheets("Cockpit & As_Gen").Cells(48, 9)
vXDistribution(k) = xDistribution
vPPA(k) = PPALevel
vIRR(k) = Worksheets("As_Yr").Cells(348, 9)
Next k
'Determines optimal FlipYear
MinIRR = WorksheetFunction.Max(vIRR)
Position = WorksheetFunction.Match(MinIRR, vIRR, False)
OptFlipYear = vFlipYear(Position)
OptxDistribution = vXDistribution(Position)
'Prints optimal setting to Excel
Worksheets("As_Yr").Cells(345, 9) = OptFlipYear 'Optimal flip year
Worksheets("As_Yr").Cells(346, 9) = OptxDistribution 'Optimal CF distrib
'restores to the original goal-seek iterations setting
IterTF = Application.Iteration = True
IterStep = Application.MaxIterations
With Application
.MaxIterations = IterStep
.Iteration = IterTF
.MaxChange = 0.001
End With
End Sub
Is this something that one of you could help me with?
I guess it is a dummy mistake, but I can't figure that out.
Many thanks,
Alice

Excel Diagramm Seriesnames in VBA

I'm programming a Makro for a Excel xy-Diagramm
The diagramm is nearly correct, but i have dublicate DataSeriesNames;
I already tried to go through all Series and Compare the Names.
There were no Errors, but it didn't work.
Code was like that:
For a=1 to Count
If ActiveChart.SeriesCollection(Count).Name = Range("A2").Value Then
Name = true
End If
a = a + 1
Next
If Name = false Then
ActiveChart.SeriesCollection.NewSeries
End If
ActiveChart.SeriesCollection(Count).Name = "='Tasks'!$D$" & i
ActiveChart.SeriesCollection(Count).XValues = "='Tasks'!$B$" & i
ActiveChart.SeriesCollection(Count).Values = "='Tasks'!$C$" & i
Mfg Robin
There are a couple of things wrong here.
First of all, you're always looking at the same series! I think you want to replace Count with a in your If statement.
If ActiveChart.SeriesCollection(a).Name
Secondly, once that is corrected, even if your Name variable gets set to True at some point, it may get reset to False later as the For...Next loop continues iterating through the remainder of the series collection. To prevent this, add an Exit For like this:
For a = 1 To Count
If ActiveChart.SeriesCollection(a).Name = Range("A2").Value Then
Name = True
Exit For
End If
a = a + 1
Next
Also, I suspect you haven't declaring Name as a Boolean variable, so by default it's a Variant so its value isn't False to start with! You should declare the variable at the top of your procedure with Dim Name as Boolean, and then if you want Name to be False by default, you should really say so explicitly: Put Name = False before the loop. Moreover, Name is a terrible name for a variable... and so is Count Argh! I think your code should look like this:
Option Explicit
Sub MySub()
Dim a As Long
Dim NameExists As Boolean
Dim SeriesCount As Long
SeriesCount = ActiveChart.SeriesCollection.Count
NameExists = False
For a = 1 To SeriesCount
If ActiveChart.SeriesCollection(a).Name = Range("A2").Value Then
NameExists = True
Exit For
End If
a = a + 1
Next
If NameExists = False Then
' Rest of your code goes here...
End Sub

Resources