creating a loop in vba for an excel macro - excel

I have recorded a macro in Excel that takes data from certain cells in one page of a spreadsheet and copies them to page in a different order. it does each cell individually, and is quite long.
However it only does it for one row of data in the first page.
How do I make this single macro into a loop that copies the same data but from each row into the new page?
I haven't included the macro code since it is very long but can do so if necessary.
Thanks

You could omit your code to only show the relevant part, or code a mockup macro to address only and only your problem.
Lets imagine your problem as a sub, which in this case is highly omitted:
Sub OmittedSub()
' Do stuff
End Sub
You can create new sub to call it many times, this new sub would be the one you would be calling instead:
Sub LoopOmittedSubs()
Dim i As Integer
' Loop to call your macro routine multiple times
For i = 1 To 100
OmittedSub
Next
End Sub
In case you would need to pass a value, for example your macro does not know which row to affect and you would need to tell it, you can pass the loop variable like this:
Sub OmittedSub(iRow As Integer)
' Do stuff for row number iRow
End Sub
Sub LoopOmittedSubs()
Dim i As Integer
' Loop to call your macro routine multiple times
For i = 1 To 100
OmittedSub i
Next
End Sub
This answer is the very basics of VBA. I dont know how to answer your question better without knowing what you already tried, how you tried, etc...

Raybarg provided you basic solution to that problem. I am not sure what do you mean by "certain cell", does it mean they have certain value or there are in regular order like A5, A10, A15?
In both cases you probably will use Raybarg's code and conditional statements.
You should include your code, it gives some hints on what you actually want to achieve and where is error.

Related

Insert VBA sub into Excel Worksheet

Good day,
I am using Excel 2013 and I would like to hide and unhide my Sheets as I work with them. I spent some time Googling around and found plenty of ancient posts on forums about adding VBA to modules, but that's not quite what I'm looking for.
On a main page where I spend most of my time using data, I have a button that shows a UserForm with a list of sheets in a ListBox. I choose the Sheet from the ListBox, hit OK, and it runs the following;
Private Sub OKButton_Click()
ThisWorkbook.Sheets(JobListBox.value).Visible = xlSheetVisible
ThisWorkbook.Sheets(JobListBox.value).Activate
Unload Me
End Sub
I would like it so when I have my new sheets created via VBA, I can populate the sheet with the following subroutine;
Private Sub Worksheet_Deactivate()
Me.Visible = xlSheetVeryHidden
End Sub
If anyone can let me know how I can make a Subroutine to insert this code into my sheets, I would greatly appreciate it.
PS: My fallback method is to, of course, just copy/paste the code manually... But I would prefer to automate it if possible.
Instead of adding the same code to each sheet, since they are all inside the workbook and you are really trying to execute a hide once any sheet in the workbook is deactivated, put this in the code for ThisWorkbook.
Private Sub Workbook_SheetDeactivate(ByVal Sh As Object)
Sh.Visible = xlSheetVeryHidden
End Sub
You might be able to use more workbook events with your type of project.
Here is a list of the workbook events.
If you want to exclude your main page from this, you can modify this by adding an IF statement:
Private Sub Workbook_SheetDeactivate(ByVal Sh As Object)
IF Sh.Name <> "Main" Then
Sh.Visible = xlSheetVeryHidden
End If
End Sub
The main line of thinking being that if you have to put the same code into more than one object, let alone ALL of them, you are repeating yourself.
Check out the concept of DRY, or "Don't Repeat Yourself", unless you like it WET, "We Enjoy Typing". or "Write Everything Twice". Even if it's just going to be created programmatically, a chunk of code shouldn't have to exist in all your sheets exactly the same when you can have one piece of code have an incoming argument that is a worksheet.
This way, if you have to make a change to its behavior, you do it once. It's easily testable and less to keep track of or modify later.
So if you find yourself having to use the same code over and over, look to the parent object and try to find a way to pass the changing object or variable through as an argument to a singular piece of code, or module.
Also, this is probably why you aren't finding any results on inserting the same code into every sheet. It's not a good practice
Article on DRY

Automatically Run Macro When Data Is Pasted VBA

I have a worksheet where in the first three columns (A,B,C) I store data. These values are used in a macro.
I would like to know how it is possible to make this macro run automatically after data is pasted onto these columns. I am almost sure that I will use the Worksheet-Change module, but as for the code I am clueless.
Thanks in advance.
A simple implementation:
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Range("A1:C" & ThisWorkbook.Worksheets(1).UsedRange.Rows.Count)) Is Nothing Then
'Call your Macro to do stuff
End If
End Sub
Intersect checks if Target is in the range you want to monitor. So if something changes in columns past C, Intersect will return Nothing and your macro won't be called. Just keep in mind that the Worksheet_Change event fires on any change, even double clicking into the cells. If all you are doing in this Worksheet is copy&pasting data and then running your Macro, this should be fine, but if you are manipulating your data further, you might have to look at more sophisticated solutions. Examples include mirroring your Worksheet and comparing it pre/post Worksheet Changed Event. You can read more on this here: Detect whether cell value was actually changed by editing

Simple vba program in Excel

Sub TEST()
If cells(i, "R").Value <> "UK" Then
cells(i, "R").Interior.ColorIndex = 3
End If
End Sub
If I run this program it throws application defined error \
I am new to Excel (beginner)
How to correct this error!!!
Thanks In advance
I think the issue is "R" that I know of the cells method takes 2 parameters one is rows the other is columns (in that order) but this is done by number not letter so if you change it to cell(1,18) then the code above works fine.
This link may also be useful to learn more, among other things it describes how you would normally select a range first as I believe your code above will assume the currently selected page, however you might want to run in on a button click from another page or as soon as the spreadsheet opens.
http://msdn.microsoft.com/en-us/library/office/ff196273.aspx
The problem is that the variable i has not been assigned a value. VBA assumes that it is zero. Since i is used to determine the row of the cell, Excel throws an exception because there is no row 0!
First you have to define i variable
for example: Dim i as variant

Excel VBA calling sub from another sub with multiple inputs, outputs of different sizes

I would like to call a sub from another sub inside in the same module. The first sub would be my main code and there I would call the second subroutine. Second subroutine receives multiple inputs as integer, double, double arrays and double matrices. The size of the arrays and matrices are known and stored in an integer variable. The sub also returns several outputs. So, I would like to do something like this.
sub Main()
Nc As integer
Dim kij(1 To Nc, 1 To Nc), xi(1 to Nc), a1 As Double
'I assign values to my variables from the excelsheet e.g. Nc=Cells(1,1) etc.
CalculateA(Nc,kij, xi, a1, a)
Cells(5,5)=a
end sub
sub CalculateA(Nc as integer,kij as matrix double, xi as array double, a as Double)
a=0
For i=1 To Nc
For j=1 To Nc
a = a + kij(i,j)*x(i)*x(j)
Next j
Next i
a = a*a1
end sub
How does it know which sub is the main sub where it starts to run. Can I put the secondary sub on top and the code somehow starts from the bottom subroutine?
To call a sub inside another sub you only need to do:
Call Subname()
So where you have CalculateA(Nc,kij, xi, a1, a) you need to have call CalculateA(Nc,kij, xi, a1, a)
As the which runs first problem it's for you to decide, when you want to run a sub you can go to the macro list select the one you want to run and run it, you can also give it a key shortcut, therefore you will only have to press those keys to run it. Although, on secondary subs, I usually do it as Private sub CalculateA(...) cause this way it does not appear in the macro list and it's easier to work
Hope it helps,
Bruno
PS: If you have any other question just ask, but this isn't a community where you ask for code, you come here with a question or a code that isn't running and ask for help, not like you did "It would be great if you could write it in the Excel VBA format."
These are really two questions.
The first one is answered here: Calling a Sub in VBA
To the second one, protip: there is no main subroutine in VBA. Forget procedural, general-purpose languages. VBA subs are "macros" - you can run them by hitting Alt+F8 or by adding a button to your worksheet and calling up the sub you want from the automatically generated "ButtonX_Click" sub.
VBA subs are no macros. A VBA sub can be a macro, but it is not a must.
The term "macro" is only used for recorded user actions. from these actions a code is generated and stored in a sub. This code is simple and do not provide powerful structures like loops, for example Do .. until, for .. next, while.. do, and others.
The more elegant way is, to design and write your own VBA code without using the macro features!
VBA is a object based and event oriented language. Subs, or bette call it "sub routines", are started by dedicated events. The event can be the pressing of a button or the opening of a workbook and many many other very specific events.
If you focus to VB6 and not to VBA, then you can state, that there is always a main-window or main form. This form is started if you start the compiled executable "xxxx.exe".
In VBA you have nothing like this, but you have a XLSM file wich is started by Excel. You can attach some code to the Workbook_Open event. This event is generated, if you open your desired excel file which is called a workbook. Inside the workbook you have worksheets.
It is useful to get more familiar with the so called object model of excel. The workbook has several events and methods. Also the worksheet has several events and methods.
In the object based model you have objects, that have events and methods. methods are action you can do with a object. events are things that can happen to an object. An objects can contain another objects, and so on. You can create new objects, like sheets or charts.

Having Excel Fields Auto Update when New Data Added

I have an Excel doc that starts with some fields that come from calculations done on the rows below it. To do the calculations I currently have a module with about 4 functions that loop through rows 20 through N(first blank cell). These functions are called straight from the cells at the top of the sheet. The problem is that the calculations at the top are not updating whenever someone adds/removes data from the rows below. How can this be accomplished?
If your functions are Excel VBA user-defined functions called from worksheet cells, then you will get this not-recalculating behaviour if the UDF refers to cells that are not in the input parameters of the UDF.
If this is the case a good solution would be to define some Dynamic Named Ranges that expand/contract as data is added/deleted and use them as input to the function.
Another solution would be to add Application.Volatile to your UDF, but this has the undesirable side-effect that your UDFs will be recalculated at every calculation which can be painfully slow.
If I understand your question correctly, you can use Worksheet_Change event to accomplish such tasks.
In your sheet module, add a Worksheet_Change event:
Private Sub Worksheet_Change(ByVal rngChanged As Range)
' Call your subs and functions here
MsgBox "You just changed something!"
End Sub
Note that the Worksheet_Change sub must have one and only one argument of type Range. Excel will make it a reference to the range that was changed by the sheet user. If you want to observe its behaviour, try placing this line in the sub:
rngChanged.Interior.ColorIndex = 4
Read more e.g. here.

Resources