I am trying to create an array of a user set length that users can add values to that will be saved and output on multiple sheets. I am very new to VBA so I do not know if what I am trying to do is possible but I have tried a few methods unsuccessfully.
This is the code I have so far
Sub addCost()
Dim costArray() As Variant
ReDim Preserve costArray(1 To Range("b2").Value)
For i = 1 To Range("b2").Value
costArray(i) = 0
Next i
Dim newCost As Variant
Dim costYear As Variant
newCost = InputBox("New cost amount:")
costYear = InputBox("Year new cost is active:")
costArray(costYear) = newCost
End Sub
Here is what the input tab looks like in excel
With the length of the array being the project lifespan and the add new cost activating the code, clear costs are still in progress. Is there a way for the array to store after multiple executions of the addCost sub?
Thanks!
This link Microsoft shows some methods of store values after the macro ending (in your case, sub addCost)
I think the first solution will be good for you.
Other solutions is use Access to store data (specially if you need these data over time) or a new and clean worksheet where you can store array entries in a cell (This is a very practical solution if the number of entries does not get too big)
I currently have a full code written to copy the output of one spreadsheet, into certain columns of another spreadsheet. This is part of a project at work, but the VBA codes left to me from an employee that resigned, don't apply well. It's pretty simple in theory.
What I want it to do is pull the value in BB183 from the tab 737-10_1b28_routes in the file 737-10_1b28_routes.csv, and paste it in the tab 737-10 Scenario 1 of file Aero Sales Support Modified Att.1 Performance Data Attachment and Fill in Form_20220402.xlsx in box L30.
I then want the code to take BB184, and place it in L32. I need the code to skip a line because I want to paste different data in the other line (BB697 goes into to L31 with the same repeating pattern for BB (+1) and L (+2). I think once I have a more efficient code, I could figure out the final solution, but need some help. I'm currently running into procedure too large.
I feel like it's j=j+2 from j=30:688 for the L column and BB is like i=i+1 from i=183:512.
Then the second part of the code is j=j+2 from j=31:689 for the L column and BB is like i=i+1 from i=697:1026.
Please see code two to see how it's altered.
Sub vba_copy_data_GCD()
Workbooks("737-10_1b28_routes.csv").Worksheets("737-10_1b28_routes").Range("BB183").Copy _
Workbooks("Aero Sales Support Modified Att.1 Performance Data Attachment and Fill in Form_20220402.xlsx").Worksheets("737-10 Scenario 1").Range("L30")
Workbooks("737-10_1b28_routes.csv").Worksheets("737-10_1b28_routes").Range("BB184").Copy _
Workbooks("Aero Sales Support Modified Att.1 Performance Data Attachment and Fill in Form_20220402.xlsx").Worksheets("737-10 Scenario 1").Range("L32")
Workbooks("737-10_1b28_routes.csv").Worksheets("737-10_1b28_routes").Range("BB185").Copy _
Workbooks("Aero Sales Support Modified Att.1 Performance Data Attachment and Fill in Form_20220402.xlsx").Worksheets("737-10 Scenario 1").Range("L34")
Workbooks("737-10_1b28_routes.csv").Worksheets("737-10_1b28_routes").Range("BB186").Copy _
Workbooks("Aero Sales Support Modified Att.1 Performance Data Attachment and Fill in Form_20220402.xlsx").Worksheets("737-10 Scenario 1").Range("L36")
Workbooks("737-10_1b28_routes.csv").Worksheets("737-10_1b28_routes").Range("BB697").Copy _
Workbooks("Aero Sales Support Modified Att.1 Performance Data Attachment and Fill in Form_20220402.xlsx").Worksheets("737-10 Scenario 1").Range("L31")
Workbooks("737-10_1b28_routes.csv").Worksheets("737-10_1b28_routes").Range("BB698").Copy _
Workbooks("Aero Sales Support Modified Att.1 Performance Data Attachment and Fill in Form_20220402.xlsx").Worksheets("737-10 Scenario 1").Range("L33")
Workbooks("737-10_1b28_routes.csv").Worksheets("737-10_1b28_routes").Range("BB699").Copy _Workbooks("Aero Sales Support Modified Att.1 Performance Data Attachment and Fill in Form_20220402.xlsx").Worksheets("737-10 Scenario 1").Range("L35")
End Sub
Inspecting cell values from VBA is slow. Writing or copying values to cells from VBA is slower still. Doing these things over and over in a loop is a quick way to destroy VBA execution speed.
It is hundreds to thousands of times faster in execution speed to grab a large range and assign the values to a VBA array in one go, and then do the processing directly on the VBA array without touching any of the cells during the processing and then when done, write the entire array out to a worksheet in one go. The larger the ranges involved the greater the execution speed improvement by processing the VBA array instead of the cells directly.
Array processing is extremely fast in VBA. Worksheet cell access is extremely slow from VBA. It takes roughly the same amount of time to write a value to one cell as it does to write tens of thousands of values to a range from a VBA array. Never write individual cell values in a loop!
Using .Offset is also slow and doing so repeatedly is ill advised. This problem is avoided completely by using the array approach.
The following routine should do the trick if I understand your range descriptions adequately. vSrc and vDst are 2D VBA arrays. All the values are processed in the arrays (not on the sheets) and then when done the array values are written to the destination worksheet in one go...
Sub vba_copy_data_GCD()
Dim c&, i&, vSrc, vDst
Const SRC_GAP& = 514
Const SRC_RANGE$ = "bb183:bb1026"
Const SRC_SHEET$ = "737-10_1b28_routes"
Const SRC_WORKB$ = "737-10_1b28_routes.csv"
Const DST_RANGE$ = "l30:l688"
Const DST_SHEET$ = "737-10 Scenario 1"
Const DST_WORKB$ = "Aero Sales Support Modified Att.1 Performance Data Attachment and Fill in Form_20220402.xlsx"
vSrc = Workbooks(SRC_WORKB).Worksheets(SRC_SHEET).Range(SRC_RANGE).Value2
With Workbooks(DST_WORKB).Worksheets(DST_SHEET).Range(DST_RANGE)
vDst = .Value2
For i = 1 To UBound(vDst) \ 2 Step 2
c = c + 1
vDst(i + 0, 1) = vSrc(c, 1)
vDst(i + 1, 1) = vSrc(c + SRC_GAP, 1)
Next
.Value2 = vDst
End With
End Sub
Given how sure I am of what you want, please make sure your files are backed-up before trying this:
Sub vba_copy_data_GCD()
Dim srcWS as Worksheet
Dim destWS as Worksheet
Dim i as Long, j as Long
Set srcWS = Workbooks("737-10_1b28_routes.csv").Worksheets("737-10_1b28_routes")
Set destWS = Workbooks("Aero Sales Support Modified Att.1 Performance Data Attachment and Fill in Form_20220402.xlsx").Worksheets("737-10 Scenario 1")
For i = 0 to 329 Step 2
With destWS
.Range("L30").Offset(i,0).Value2 = srcWS.Range("BB183").Offset(j,0).Value2
.Range("L31").Offset(i,0).Value2 = srcWS.Range("BB697").Offset(j,0).Value2
End With
j = j + 1
Next i
End Sub
I'm pretty fresh to VBA and hope one of you can help.
I have a pretty complex xls function and need to be able to update parts of the function, that is the size of the table that it refers to.
Background is that I have a constantly growing table in say sheet2 in which I use array formulas to compile some of the information I need. Since these arrays consume a lot of processing power, I made a macro in which the table is converted back to a range, then a bunch of calculations are done and it's re-formated as a table. What I didn't consider is that this re-arranging of the table stops feeding my overview sheet1 with information from that table. So what I basically need is amending an array formula in my overview sheet so that it re-adjusts to the size of the table.
The array formula that i need to change is the following:
INDEX(Transactions!$O$20:$O$77,MAX(IF(Transactions!$D$20:$D$77=Overview!B8,IF(Transactions!$C$20:$C$77<=Overview!$B$5,IF(Transactions!$K$20:$K$77=Overview!F8,ROW(Transactions!$O$20:$O$77)-MIN(ROW(Transactions!$O$20:$O$77))+1))),1))
,where row 20 is fixed, but the table expands further down (e.g. the 77 will evenutally grow to 5,000 or so)
I'm pretty stuck on this and haven't generated much (useful) code yet.
Sub UpdateOverview()
Sheet2.ListObjects("Transactions").Unlist
Dim last_row_T As Long
last_row_T = Cells(Rows.Count, "C").End(xlUp).Row
Sheet1.Range("H7").FormulaArray="=INDEX(Transactions!$O$20:$O$77,MAX(IF(Transactions!$D$20:$D$77=Overview!B8,IF(Transactions!$C$20:$C$77<=Overview!$B$5,IF(Transactions!$K$20:$K$77=Overview!F8,ROW(Transactions!$O$20:$O$77)-MIN(ROW(Transactions!$O$20:$O$77))+1))),1))"
Sheet2.ListObjects.Add(xlSrcRange, Range("C19").CurrentRegion, , xlYes).Name = "Transactions"
End Sub
I tried different versions of implementing the last_row_T into the formula, but that didn't work.
Ultimately, I need to change each of the 77 in the index formula accordingly to the growing size of the table - so it has to be a dynamic solution. Is there a way to do that or am I somewhere in nomansland?
I suggest this simple fix plus a workaround for the 255 character limit of .FormulaArray:
Dim strFormula As String, newFormula As String
strFormula = "=INDEX(Transactions!$O$20:$O$lastrow,MAX(IF(Transactions!$D$20:$D$lastrow=Overview!B8," & _
"IF(Transactions!$C$20:$C$lastrow<=Overview!$B$5,IF(Transactions!$K$20:$K$lastrow=Overview!F8," & _
"ROW(Transactions!$O$20:$O$lastrow)-MIN(ROW(Transactions!$O$20:$O$lastrow))+1))),1))"
newFormula = Replace(strFormula, "lastrow", CStr(last_row_T))
Sheet1.Range("H7").FormulaArray = "FunctionPlaceholder()"
Sheet1.Range("H7").Replace "FunctionPlaceholder()", newFormula
See this question and this link for more information on the workaround.
So I have a Variant that is storing keys from a Dictionary. I need to put these values into a table but as far as I can tell the data source for a table has to be a range. Is there anyway around this? If not, is there a way to convert my variant to a range?
(Extra details about the Dict and Variant)
Both rely on imported data so there are no fixed values or even number of values, making my issue that much more complicated.
I've tried looking around for answers to this as I am at a complete loss - this is well beyond my current knowledge of vba - but what little I did find didn't seem to work.
Here's the code (only for creating the table but can provide more if needed) without any lines trying to convert the xInput. xInput is the Variant and hashTbl is the Dictionary.
ReDim xInput(0 To hashTbl.Count - 1) 'Redefine xInput as hashTbl values
For i = 0 To hashTbl.Count - 1
xInput(i) = hashTbl.Keys(i)
Next i
Set objTable = ActiveSheet.ListObjects.Add(xlSrcRange, xInput, Selection, , xlYes)
objTable.TableStyle = "TableStyleMedium2"
Of course, I want the table to be populated with the data contained in xInput but all I get is "Runtime Error - 5 Invalid Procedure Call or Argument"
Any help would be much appreciated.
I have a sheet that the values of a range change each time I change a specific cell. Let's say that the cell C8 is an indentity of a person and column H the scheduled monthly repayments. I need to find the aggregate monthly repayments, hence on each possible value of C8 (and that actually means for every person as you can think of different values of C8) I need the aggegate of repayments, hence the aggegate of cell Hi Hence, keeping row i constant and changing cell C8, I always need to sum Hi. So I actually need sum(Hi) (i constant and the index of the sum is cell c8, so if c8 takes value from 1 to 200, I need the sum(Hi(c8)), again row i . Hi(c8) it is just a notation to show you that Hi depends on the value of c8. The actual formula in cell H10 is INDEX('Sheet2'!R:R,MATCH('Sheet1'!$C$8,'Sheet2'!F:F,0)))). H11 and onwards have the same formula with slight twists for the fact that the repayments are not always equal, but the index function remains the same.
Then, the total of H10 for all possible values of c8 is pasted in c17, the total of H11 is pasted in C18 etc. Please find some images below, maybe that helps to support what I try to achieve. enter image description here
I have the following code for that purpose. Note that the above example was just to explain you a bit the background, the cells and the range that changes are different.
sub sumloop()
Application.ScreenUpdating = False
Application.DisplayStatusBar = False
Sheets("Sheet1").Range("C8").Value = 1
Dim i, k As Integer
i = 1
k = Sheets("Sheet1").Range("C9").Value
Dim LR As Long
LR = Sheets("Sheet1").Range("C" &
Sheets("Sheet1").Rows.Count).End(xlUp).row
Sheets("Sheet1").Range("C17:C" & LR).ClearContents
Do While i <= k
If (Sheets("Sheet1").Range("J9").Value = "") Then
Sheets("Sheet1").Range("h10:h200").Copy
Sheets("Sheet1").Range("c17").PasteSpecial
Paste:=xlValues, Operation:=xlAdd, SkipBlanks:= _
False, Transpose:=False
Else
Sheets("Sheet1").Range("h9:h200").Copy
Sheets("Sheet1").Range("c17").PasteSpecial
Paste:=xlValues, Operation:=xlAdd, SkipBlanks:= _
False, Transpose:=False
End If
Sheets("Sheet1").Range("C8").Value = Sheets("Sheet1").Range("C8").Value+1
i = i + 1
Loop
Sheets("Sheet1").Range("C8").Value = 1
Application.ScreenUpdating = True
Application.DisplayStatusBar = True
End Sub
The if inside of the loop is needed as the location of the first value of the range depends on some criteria which have not to do with the code. Also k denotes the maximum number of possible values. What I need is approximately 250.
While the code works, it takes approximately 40 seconds to run for 84 values of cell C8 and approximately 1.5 minute for 250. I tried some things, changed do while to for but nothing significant, used variable ranges instead of fixed ones like h10:h100, very similar to what I do with Sheet1.Range(C17:C&LR). Again no significant changes. As I am very new to vba I don't know if 1.5 minutes are a lot for such a simple code, but to me it seems a lot and this analysis is needed for 10 different combinations of 250 different values for cell c8, which means 15 minutes approximately.
I would appreciate if anyone can suggest me something faster.
Thank you very much in advance.
Here is a complete solution, with explainations in comments.
Because we do not have you source spreadsheet, I could not run any tests on this.
Option Explicit 'This forces you to declare all your varaibles correctly. It may seem annoying at first glance, but will quickly save you time in the future.
Sub sumloop()
Application.ScreenUpdating = False
'Application.DisplayStatusBar = False -> This is not noticely slowing down your code as soon as you do not refresh the StatusBar value for more than say 5-10 times per second.
'Save the existing Calculation Mode to restore it at the end of the Macro
Dim xlPreviousCalcMode As XlCalculation
xlPreviousCalcMode = Application.Calculation
Application.Calculation = xlCalculationManual
'Conveniently store the Sheet into a variable. You might want to do the same with your cells, for example: MyCellWhichCounts = MySheet.Range("c17")
Dim MySheet As Worksheet
MySheet = ActiveWorkbook.Sheets("Sheet1")
MySheet.Range("C8").Value2 = 1 'It is recommended to use.Value2 instead of .Value (notably in case your data type is Currency, but it is good practice to use that one all the time)
Dim LR As Long
LR = MySheet.Range("C" & MySheet.Rows.Count).End(xlUp).Row 'Be carefull with "MySheet.Rows.Count", it may go beyond your data range, for example if you modify the formatting of a cell below your "last" row.
MySheet.Range("C17:C" & LR).Value2 = vbNullString 'It is recommended to use vbNullString instead of ""; although I agree it makes it more difficult to read.
Dim i As Integer, k As Integer 'Integers are ok, just make sure you neer exceed 255
k = MySheet.Range("C9").Value2
For i = 1 To k 'Use a For whenever you can, it is easier to maintain (i.e. avoid errors and also for you to remember when you go back to it years later)
'Little extra so you can track progress of your calcs
Dim z As Integer
z = 10 'This can have any value > 0. If the value is low, you will refresh your app often but it will slow down. If the value is high, it won't affect performance but your app might freeze and/or you will not have your Statusbar updated as often as you might like. As a rule of thumb, I aim to refresh around 5 times per seconds, which is enough for the end user not to notice anything.
If i Mod z = 0 Then 'Each time i is a mutliple of z
Application.StatusBar = "Calculating i = " & i & " of " & k 'We refresh the Statusbar
DoEvents 'We prevent the Excel App to freeze and throw messages like: The application is not responding.
End If
'Set the range
Dim MyResultRange As Range
If (MySheet.Range("J9").Value2 = vbNullString) Then
MyResultRange = MySheet.Range("h10:h200")
Else
MyResultRange = MySheet.Range("h9:h200")
End If
'# Extract Result Data
MyResultRange.Calculate 'Refresh the Range values
Dim MyResultData As Variant
MyResultData = MyResultRange.Value2 'Store the values in VBA all at once
'# Extract Original Data
Dim MyOriginalRange as Range
MyOriginalRange.Calculate
MyOriginalRange = MySheet.Range("c17").Resize(MyResultRange.Rows.Count,MyResultRange.Columns.Count) 'This produces a Range of the same size as MyResultRange
Dim MyOriginalData as Variant
MyOriginalData = MyOriginalRange.Value2
'# Sum Both Data Arrays
Dim MySumData() as Variant
Redim MySumData(lbound(MyResultRange,1) to ubound(MyResultRange,1),lbound(MyResultRange,2) to ubound(MyResultRange,2))
Dim j as long
For j = lbound(MySumData,1) to ubound(MySumData,1)
MySumData(j,1)= MyResultData(j,1) + MyOriginalData(j,1)
Next j
'Instead of the "For j = a to b", you could use this, but might be slower: MySumData = Application.WorksheetFunction.MMult(Array(1, 1), Array(MyResultData, MyOriginalData))
MySheet.Range("C8").Value2 = MySheet.Range("C8").Value2 + 1
Next i
MySheet.Range("C8").Value2 = 1
Application.ScreenUpdating = True
Application.StatusBar = False 'Give back the status bar control to the Excel App
Application.Calculation = xlPreviousCalcMode 'Do not forget to restore the Calculation Mode to its previous state
End Sub
Added by OP (see comments)
Image 1 Code written in the initially question. enter image description here
Image 2 Code above enter image description here
OK, A few things.
Firstly, Dim i, k As Integer doesn't do what you think it does, you need to do: Dim i As Integer, k As Integer
Secondly don't use Integer in VBA use Long so Dim i As Long, k As Long
Third the calculations are killing you. Turn them off with Application.Calculation = xlCalculationManual at the start of your code and back on with Application.Calculation = xlCalculationAutomatic at the end of your code.
Now we are presented with really fast code but the problem that it doesn't update on each iteration which you need it to do. You can calculate just a range like so: Sheets("Sheet1").Range("h10:h200").Calculate so put that in just before you copy the range
There will be an even faster way to do this but I just can't seem to wrap my head around your requirements so I am unable to assist further.
Welcome to StackOverflow.
I must admit I got a bit confused by your narrative, as I did not fully understand if you are doing a sum(a,b,c) or a sum(sum(a,b,c), sum(d,e,f), ...).
In any cases, a trick that will dramatically accelerate your script is the use of arrays.
Performing calcs with VBA is not slow, but retrieving the data from Excel (communicating with the application) IS slow, and pretty much depending on the number of "requests", rather than the quantity of data requested.
You can use arrays to request the data from a range all at once, isntead of requesting the value of each cell separately.
Dim Arr() As Variant
Arr = Range("A1:E999")
It is as simple as this.
Give it a try and if you are still struggling let us know.
BONUS
If you are new to Arrays, keep in mind you can have a two-dimmensionnal array:
Dim 2DArray(0 to 10, 0 to 50)
Or a stacked array (an array of arrays):
Dim MyArray() as String
Dim StackedArray() as MyArray
Dim StackedArray() as Variant
You will need a 2D-Array for extracting the data from a range, but I feel you may need an Array of 2D-Arrays for your Sum of Sums.
Some recommended reading: https://excelmacromastery.com/excel-vba-array/
How to achieve the same through pivot charts (no VBA)
Step 1
First, you must organize your data in a specific way, where each column is a field, and each row is a data entry. If you are not familiar with databases, this is the most tricky point as you may arrange your data in different ways.
Long story short, we will take an example where you have 3 customers and 4 dates.
So that is 12 data entries, which will provide the repayment value for each of the possible customer ID and date.
Step 2
Select that data and insert a PivotChart.
Note: you could insert a PivotTable alone, or a PivotChart alone. I recommend the option hwere you insert both, as managing your data will be more intuitive when working on the Chart. The table is updated at the same time you update the chart.
Step 3
Make sure the all your data is selected, including the top row which will dictate the name of each field (the name of each column).
Step 4
A new sheet has just been create, and you can see where both your PivotTble and PivotCharts will appear. Select the chart.
Step 5
A menu to the right will appear (it might have already been there, so make sure you selected the Chart and not the Table, as that menu would be slightly different).
Step 6
Drag and drop the field names into the categories as shown.
What you are doing here is telling Excel what data you want to see (Values) and how you want to break it down (per date, and per customer).
Step 7
By default dates data is always groupped quartile and year. To be able to see all the date we have data for, you can click the [+] near the data on the Table: this will show more details for both the table and the chart.
Step 8
But we want to get completely rid of the quartils and years. In order to achieve this, you need to right click any value of your date column in the Table, and choose "Ungroup" as displayed.
Step 9
Your data now looks like this.
Note the time axis is not on scale. For example if you hae monthly data and a month is missing, there will be no gap. This is one of the difficulties with Pivot data. This can be overcomes, but it is off topic here.
Step 10
Now we want to have a cumulative view of the data, so we want to play with the way the values are proessed by Excel.
Select the chart, then in the right panel: right click on the "Sum of Repayment" field, and select "Value Field Settings".
Step 11
In the "Show Values As" tab, select "Show values as" "Running Tital In".
Then choose "Date".
Here we are telling Excel that the value to display should be a cumulative total, cumulated according to the "Date" field.
Press OK.
Step 12
You now have what you are looking for. If you look in the Table, you have one column per Customer ID, and one row per date. For a given Date, you have the cumulative repayment made by a given Customer ID. At the very right, you have the Grand Total, which is, for a given date, the sum of all the Customer ID values.
Step 13
The Chart keeps showing the cumulative payment per CUstomer ID, and we cannot see the grand total.
In orer to achieve this, simply remove the "Customer ID" field from the "Legend (Series)" category area in the Fields Panel, as shown. (you can untick the Customer Id [x] box, or you can drag and drop it from the category area to the main list area).
Step 14
Now we only have the Grand total in the chart. But why?
If you display the "Value Field Settings" of Sum of Repyament" (Step 10), the first tab "Summarize Values By" will tell Excel what to do when several value meet the same Legend and Axis values.
Now that we removed the Customer ID field from the Legend area, for each date, we have 3 repayment values (one for each Customer ID). In the field settings, we tell Excel to use a "Sum". So it returns the sum of the 3 values.
But you could play around and return the Average, or even use "Count", which will show you how many records you have (it will return 3).
That is why pivot charts are so powerful: with only a few clicks and/or drag and drop, you can display a myriad of different graphics for your data.
For future interest, you should look online for Filters, and "Insert Slicer" (which is equivalent to filtering, but will add button directly on your chart: great when showing the data to colleagues and switch from one setting to another)
Hope this helped!