Incrementing cells: a VBA logic algorithm [closed] - vba

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I am trying to fill cells from A3 to A100 with numbers, as shown. Every three cells, the cell value increases of 1 digit. More than having the VBA snippet as an answer, which would be great, I would really appreciate if someone could be kind enough to make a step by step explanation of the logic behind building the code. I need to understand to racionalize on this in order to apply this knowledge in future and more complex endeavours.
A3 ---> 1
A4 ---> 1
A5 ---> 1
A6 ---> 2
A7 ---> 2
A8 ---> 2
A9 ---> 3
A10 --> 3
A11 --> 3
A12 --> 4
A13 --> 4
A14 --> 4
( . . . )

Manually, in A3 enter:
=ROUNDUP(ROWS($1:1)/3,0)
and copy down.
So with VBA:
Sub qwerty()
Range("A3:A100").Formula = "=ROUNDUP(ROWS($1:1)/3,0)"
End Sub
If you did not want formulas in the final result:
Sub poiuyt()
With Range("A3:A100")
.Formula = "=ROUNDUP(ROWS($1:1)/3,0)"
.Value = .Value
End With
End Sub

VBA approach via datafield array and flexible row settings
Just to show another possible approach using a datafield array and allowing to define even individual start and end rows based on #CalumDa 's modified formula (assuming that you start always with 1, 1, 1 in the first three rows):
Code
Option Explicit
Sub FlexibleRange()
Dim ws As Worksheet: Set ws = ThisWorkbook.Worksheets("MySheet") ' << change to your sheet name
Dim start As Long, last As Long, i As Long ' declare variables
start = 3: last = 100 ' << change to your individual rows
Dim v: ReDim v(start To last, 1 To 1) ' variant datafield array, counter
For i = start To last: v(i, 1) = Int((i - start) / 3) + 1: Next i ' calculate values
ws.Range("A" & start & ":A" & last) = v ' write numbers to column A
End Sub

Put in
A3 = 1
A4 = 1
A5 = 1
A6 = A3 + 1
A7 = A4 + 1
A8 = A5 + 1
Then copy A6 to A8 down to A100

Why do you need to use VBA here? You can use the following formula on the worksheet. It doesn't depend on cells above so it'll give you the right answer whichever row you place it on:
=INT((ROW()-3)/3)+1
If you really want VBA there's not much to explain about this. It just places the same formula in the cells you require:
Public Sub FillColumnA()
ThisWorkbook.Worksheets("Sheet1").Range("A3:A100").Formula = "=INT((ROW()-3)/3)+1"
End Sub

Related

Format rows based on multiple values in a column

I am new to VBA and, most of the time, I either find a code here or record a macro then change it for my needs. This time I couldn't find a proper code to change thus I need your help.
Assume that I have a table as below;
A B C
Account Name Surname
1 111 AA BB
2 111 AA BB
3 111 AA BB
4 222 CC DD
5 333 EE FF
6 333 EE FF
I want to fill the entire row with different colors (ie. 2 colors like a table formating) if "Account" column contains same values. Here, for example, rows 1-2-3 will be red, row 4 will be green, rows 5-6 will be red again. When the macro reaches the last cell it will stop.
I tried to modify conditional formatting codes however I couldn't manage it. They generally work on cells in a column based on some criteria.
Any help will be appreciated.
Many thanks in advance!
This can also be done without using VBA.
We can be sneaky by using RANK and MOD to identify "alternating groups", since Conditional Formatting works with any formula that returns only a TRUE/FALSE.
Using your example data (except row numbers adjusted to account for heading):
Instructions:
Select A2:C2; set the Fill Color to Light Red. Then with A2:C2 still selected:
Home (ribbon menu) > Conditional Formatting > New Ruleā€¦
Choose Use a formula to determine which cells to format
Choose Format cells where this value is true and enter formula:
=MOD(RANK($A2,$A:$A,1),2)=1
Click Format > Fill (tab) > Light Green > OK > OK
Ctrl+C to copy (while still on A2:C2)
Select A2:C7 and Paste Special > Formats
A simple If-Then Statement seems to be all you need. Try to follow what this code is doing below:
Sub ColorCode()
Dim thisAccount, lastAccount As String
Dim NumRows, colorValue As Integer
Dim isFirstRow As Boolean
NumRows = Sheets("Sheet1").Range("A" & Rows.Count).End(xlUp).Row
lastAccount = ""
isFirstRow = True
With Sheets("Sheet1")
For i = 1 To NumRows
thisAccount = .Range("A" & i).Value
If isFirstRow = False Then
If thisAccount <> lastAccount Then
If .Range("A" & i - 1).Interior.ColorIndex = 3
.Range("A" & i).EntireRow.Interior.ColorIndex = 4
Else
.Range("A" & i).EntireRow.Interior.ColorIndex = 3
End If
Else
colorValue = .Range("A" & i - 1).Interior.ColorIndex
.Range("A" & i).EntireRow.Interior.ColorIndex = colorValue
End If
Else
.Range("A" & i).EntireRow.Interior.ColorIndex = 3
End If
lastAccount = .Range("A" & i).Value
isFirstRow = False
Next
End With
End Sub
As opposed to the previous answer, this should account for the first row by using the initial If-statement asking if it's the first row, and because we change it's value later, the only time it will run is on the first row.
Simply put, I loop through the total number of rows in the data, ask it if the account number is the same as the previous one, and if it is, I color code them the same, and if it's not, I color code them different. I just ran this myself with some made up data and seems to work perfect.
Happy coding and next time try to ask a more code specific question!
Conditional formatting is still the way to go here.
I have to point out, that your coloring logic ("color row in respect to previos cell in row A") does not apply to the first row, and thus has to fail.
If you absolutely need to use VBA, this is the logical path you want to follow:
set column A as a range
for each cell in this range, compare this cell to the previous one (again, row 1 does not work here)
color the row based on this comparison
If you need help with the coding, update your question with what you have tried so far.

VBA - Add Sheets based on a value and name accodingly [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I am having trouble with my code. I need to create new sheets and name them according to the name of a machine. Which is the range "B" & (12 * x - 5). Yes the range changes based on x which in this example is equal to 1 to 33, and is within the proper For statement. However my code is creating a large number of sheets and not just 11, in this example. Sheets("Tool Setup").Range("C18") = 11 in this example. Also, my intention is to name these sheets according to the value in Range "B" & (12 * x - 5).
Dim Sheetcnt As Integer, Tabs As Integer
Sheet = ThisWorkbook.Names(Sheets("Reporting").Range("B" & (12 * x - 5))).RefersToRange.Value
Sheetcnt = Sheets("Tool Setup").Range("C18")
For Tabs = 1 To Sheetcnt
Sheets.Add After:=Sheets(Sheets.Count) 'creates a new worksheet
Sheets(Sheets.Count).Name = Sheet 'renames the new worksheet
Next Tabs
If someone can help me figure out how to create a code that will satisfy this problem, it would be much appreciated. I have a hunch it has to do with the variable Tabs.
Thank you in advance.
Based on what you've provided, I've come up with the code below which names 11 sheets according to a formula similar to yours. To demonstrate that it works, I placed consecutive numbers in the first 127 rows of Column B of the active sheet. Then, the code calculates which row to grab using the formula Range("B" & (12 * i - 5) That formula gives the following sequence: 7 19 31 43 55 67 79 91 103 115 127, and so 11 sheets with those numbers are made.
If this is not what you intended, perhaps you can use this working code as a place from which to start. Or, better yet, provide more definition for your question.
Option Explicit
Sub sheetNamer()
Dim num As Integer, i As Integer, sh As Worksheet
num = 11
Set sh = ActiveSheet
For i = 1 To num
Sheets.Add After:=Sheets(Sheets.Count)
Sheets(Sheets.Count).Name = sh.Range("B" & (12 * i - 5))
Next i
End Sub

excel vba input reference cell into formula and loop

I have what I thought was a very basic VBA challenge, and have spent hours searching for an answer. Thanks if someone can point me to the right place if already addressed.
I have a formula that is B1 + C1 = D1, and have two 1x5 matrix of data inputs, one for cell B1 and one for cell C1, say [1,2,3,4,5] and [A,B,C,D,E], respectively, in cells (B2:B7) and (C2:C7). I would like to loop through the inputs, such that I get five unique answers [1+A, 2+B, 3+C, 4+D, 5+E], and output those answers in an adjacent 1x5 matrix, say in cells (D2:D7).
Recording a macro does not work here, as it records a copy/paste action that is inflexible for future use (for expanded matrices, other sheet locations, more complex formulas, etc).
Any help much appreciated.
Henry
UPDATE: I believe I need to be using "Do While" or some similar loop code, and additional "For" and "Next" coding.
UPDATE: Here is a step-by-step picture of what I am trying to do with the code:
step-by-step process results image
Here's the solution code:
Sub IterationMacro()
'Declare Variables
Dim h, i, j, k As Integer
Dim mySheet As Worksheet
Dim myAnswer As String
'Set Worksheet
Set mySheet = ActiveSheet
'Set # of Iterations
h = Range("B2").Value
'Clear Previous Contents
Range("C4:D4").ClearContents
Range("e5:e11").ClearContents
'Run Through Loops
For i = 5 To h + 4
For j = 3 To 4
mySheet.Cells(4, j).Value = mySheet.Cells(i, j).Value
Next
'Calculate Workbook
Calculate
mySheet.Cells(i, 5).Value = mySheet.Cells(4, 5).Value
Next
End Sub
If you could draw a table or something to use as an example, it might help.
Assuming I'm undersatnding you, you want to use a formula in D1, and fill down to D7, resulting in showing B+C=D in each row:
Range("D1").Formula="=B1+C1"
Range("D1:D7").Filldown
Edit:
Having been given the example image, it looks like you want math to happen in Row 2 (headers in Row 1). In Row 2 you want to pull up values from Row "i" and add them in Row 2, then paste the answer of that sum in Row "i".
Dim i as Integer 'i is the variable for the loop
For i = 3 to 9 'based on the picture, 3 to 9 are the 1 through 7 values
Cells(2,1).Value=Cells(i,1).Value 'pulls up Column A value from the loop to Row 2
Cells(2,2).Value=Cells(i,2).Value 'pulls up Column B value from the loop to Row 2
Cells(2,3).Formula="=A2+B2" 'Sums A2 and B2 into C2
Cells(2,3).Copy Cells(i,3) 'Copies the summed value to Row "i" in Column C
Next i 'Moves to next "i" in the loop
Let me know if that is more to your point.
Edit:
With dynamic ranges, you still know your starting point. You would look at something similar to:
Dim i as Integer
Dim LR as Long
Dim LC as Long
LR=Cells(Rows.Count,"A").End(xlUp).Row
LC=Cells(1,Columns.Count).End(xlToLeft).Column
For i = 3 to LR 'Still starting at 3, because of the example
Cells(2,1).Value=Cells(i,1).Value
Cells(2,2).Value=Cells(i,2).Value
Cells(2,LC+1).Formula="=A2+B2" 'Note the LC+1 goes one row BEYOND the last column
Cells(2,3).Copy Cells(i,LC+1)
Next i
In the last example, you can see syntax for dynamic ranges. Note that LR and LC are defined outside of the loop and do not change for the duration of the subroutine.

Check and increment the count on another sheet based on the data in this sheet

I have two sheets in a workbook. I want to find the input given in one sheet and increment the count in another sheet. For eg, I am having nearly 25 questions and the answers to the questions would be Yes / No / n/a. I have kept a drop down input selector for these three options. After the 25 questions have been answered with either of these three options, at the click of submit button, I want the count of number of yes, no and N/As. For eg. 9 N/As, 10 Yes and 6 No.
The point is, I am planning to use the Sheet 1 as a form and Sheet 2 as the accumulation of results. So it needs to check the previous counts of Yes/No/N/As and increment the count.
The code I have tried at this point is as follows,
Sub Button3_Click()
Dim sht1 As Worksheet
Dim sht2 As Worksheet
Set sht1 = ThisWorkbook.Sheets("Table 1")
Set sht2 = ThisWorkbook.Sheets("Sheet1")
sht2.Range("A2") = sht1.Range("D8")
sht2.Range("B2") = sht1.Range("D9")
sht2.Range("C2") = sht1.Range("D10")
End Sub
This macro is assigned to the submit button and the macro copies the data(Yes,No,N/As) to another sheet. I want to find the count on A2,B2,C2 and increment it with number of Yes,No and N/As.
Can anybody help me in doing this?
Assuming you have two sheets in your workbook labeled "Table 1" and "Sheet1".
Assuming "Table 1" cell D8 contains the number of Yes's (probably computed by a COUNTIF or COUNTIFS), and similarly D9 contains Number of Nos and and D10 contains the number of N/As.
Your code works, but you seem to mention that you want to increment.
If so, you probably want
sht2.Range("A2") = sht2.Range("A2") + sht1.Range("D8")
sht2.Range("B2") = sht2.Range("B2") + sht1.Range("D9")
sht2.Range("C2") = sht2.Range("C2") + sht1.Range("D10")
If all you want is the total numbers of Yes, No, N/A in the 25 questions, then there is no need for a macro. Assuming that the answers to the 25 questions are in cells D8 to D32, on the other sheet you would write:
Cell A1: Yes
Cell A2: No
Cell A3: N/A
Cell B1: =COUNTIFS('Table 1'!$D$8:$D$32,A1)
You could now copy the formula from B1 to B2 and B3, and they would all work.

convert two number to a range

I am going create a macro to convert two number to a range, e.g.
On excel cell A1 and A2, I input integer 1 and 5 respectively. The output will look like:
A3 1
A4 2
A5 3
A6 4
A7 5
How can I do that?
You can accomplish this without even using macros :)
in A3 type your first number.
On the Home tab go to the Editing section > Fill > Series...
Choose to have your series populated in Columns. Choose a stop value of 20 (or whatever)
Click OK
Now you will have a series of numbers 1-20 going down starting in Cell A3.
You can change your step value so that each number is incremented by 1, or 2 or 3 or whatever. You can also fill in rows instead of columns.
If you need it more automated than that just do all of that while recording a macro and see what it does then change the VBA to suit you more specific needs/come back here with some code to get advice on.
The Below COde will read the Content from the A1 and A2. According to the range it will display the result in the A series only.
enter code here
For i = Cells(1, 1) To Cells(1, 2)
Cells(1, i + 2) = i
Next i