VBA Long variable keeps resetting during a Do While loop? - vba

I'm writing some code in Excel to scan a row for a particular value, then get the cell address of that value.
lngCol = 0
search_start = "D1"
Do While current_week <> week_one
lgnCol = lngCol + 1
current_week = Range(search_start).Offset(0, lngCol)
Loop
wk_one_col = current_week.Address
Debug.Print wk_one_col
The code is mostly working and I'm not getting any errors, but the lngCol variable isn't incrementing as it should be.
In the loop, lngCol is always 1 after the first loop and lngCol+1 is adding 1 to the original value of the variable, which is zero.
What I'm not understanding is, each loop should be incrementing it. So first loop, it adds 1 to zero, setting lngCol to 1. Second loop, it adds another 1 to 1, making it 2.
I have another function this idea is based off and it works as expected. Each loop the lngCol variable increments by 1.
I know I know I need the variable itself to be out of scope from the loop, otherwise it'll keep resetting itself to zero every time. Where am I going wrong here?

Thank you to everyone who commented. The issue here was I had spelled the variable name wrong in the incrementing line:
lgnCol = lngCol + 1
Should be:
lngCol = lngCol + 1

Related

Range.find() correct coding in VBA

I want to find in a column of numbers the first number bigger than some fixed number, say 6.
Please can you tell me what do I need to put in the 'what' argument of the .find function to do that?
If the 'what' argument only accepts single values, how would I code what I want to do?
Thanks
Depending on context, i wouldn't use find, i would use a do until loop.
dim i as long
i = 1
do until cells(i,1).value > 6
i = i+1
loop
'something with cells(i,1).value
This would work when going down a column, as presented, or could be modified for across a row.
Edit1: was originally going to make this not an open ended loop, in case you don't have a result... lr would be used to find the last row of data in the column:
dim i as long, lr as long
lr = cells(rows.count,1).end(xlup).row
i = 1
do until cells(i,1).value > 6 OR i > lr
i = i+1
loop
if i > lr then exit sub
'something with cells(i,1).value

Excel VBA - why is my output value placed one cell down than expected?

I have a weird fluke that can be fixed easily, but I'd like to know why it's happening in the first place. I have a subroutine that is spitting out its value one cell down than expected. Here's the code:
Sub Reference()
On Error Resume Next
Dim Output_Row As Long
Output_Row = Range("Table1[Output]").Row
For Each cl In Range("Table1[ID1]")
Range("Table1[Output]").Cells(Output_Row, 1) = Application.WorksheetFunction.Index(Range("Table2[ID2]"), Application.WorksheetFunction.Match(cl, Range("Table2[ID2]"), 0))
Output_Row = Output_Row + 1
Next cl
End Sub
Now this should perform like a VLOOKUP and regurgitate the same ID from Table2 if it matches Table1, otherwise be blank. But this happens whenever I run it:
See how all the outputs are one cell down from where they should be? Now I can redefine Output_Row to say:
Output_Row = Range("Table1[Output]").Row - 1
That realigns the output values in the right spots. But I would like to know how it got wrong in the first place. Any thoughts?
Range.Row always returns the row number relative to the ENTIRE sheet.
On the other hand Range.Cells takes relative values.
So here you are passing an absolute value from Range("Table1[Output]").Row into a function expecting a relative value. The relative value is offset by the position of the table on the sheet AND the table header row Range("Table1[Output]").Cells(Output_Row, 1).
You could also change the location of Output_Row increment
Sub Reference()
On Error Resume Next
Dim Output_Row As Long
For Each cl In Range("Table1[ID1]")
Output_Row = Output_Row + 1
Range("Table1[Output]").Cells(Output_Row, 1) = Application.WorksheetFunction.Index(Range("Table2[ID2]"), Application.WorksheetFunction.Match(cl, Range("Table2[ID2]"), 0))
Next cl
End Sub

Excel VBA For loop in range contains gaps of 0's in sequence

I have isolated the problem and simplified the code to the root cause. More frustrating is that this loop works elsewhere without this error.
If you see the comments in the sequence here, there are 6 cells in the middle of the loop that turn into 0, and then after this 6 cell gap of 0's the loop works. I did use a msgbox to confirm the values were there. For whatever reason rows 130-135 always read as 0 though.
For x = 1 To 140
Cells(3 + x, "AW").Value = 70
'MsgBox (Cells(3 + x, "AW").Value)
'MsgBox confirms the correct value
'rows 130-135 are always empty with 0
Next
Any help greatly appreciated - very stumped at such a simple thing!
it was a simple logical error that was nested inside:
For a = 1 To Number_of_CalcRows
Cells(137 + a, "AW").Value = TenkanCurrent
Next
The problem was that I has not declared the TenkanCurrent with a value.

For loop to print control characters

Alright, so I am editing a Macro for Reflection Workspace Terminal Emulator. I have a macro (it is long and not necessarily relevant, I can post the full code if anyone wants, it is about a page)
At the very end of the macro, a "Good Morning" Message is printed, and then also the value of a string variable named myName. This works fine.
What I want to do is then use a For loop to print a number of control characters (tab) equal to the amount printed in the Good Morning User. Here is the code I have so far:
Dim X As Integer
For i = 1 To i = (13 + Len(myName)) 'Good Morning + a space character will always = 13
ibmCurrentScreen.SendKeys (ControlKeyCode_Tab)
Next i
End Sub
I would use the Chr() function to print the control characters, but it seems that this particular program uses ControlKeyCode_X to print them.
The For...Next loop in VBA is a simple single variable counter based loop and cannot have complex criteria or multiple counters like in some other languages (e.g. in C# for(int i = 0, int j = 10; i < 10; i++, j--)). In VBA, therefore, the i = after To is redundant because it cannot be anything other than i.
The 'For' loop in VBA therefore only specifies the counter once. It should be:
For i = startVal To endVal [step incrementVal]
...
Next [i]
i = variable to vary
startVal = start value
endVal = end value (inclusive, i.e. To 10 will include 10 as the final value)
incrementVal = optional value to increment/decrement by each loop
(default = 1)
The counter is always incremented/decremented at the end of each loop then evaluated against endVal (i.e. for a vanilla increment by one loop, after exiting the loop it will be endValue + 1).
Note (unrelated to your situation) that you can change the value of i in the loop, e.g. to increment twice because of some special circumstance.
Specifying the variable with the Next statement is optional and has no effect on behaviour (any nested loop must always be closed before an outer loop) but is good practice for reference when you have many For...Next loops so it is clear which loop the Next is closing (although you should be religiously indenting or otherwise delineating your code)
So in your case For i = 1 To (13 + Len(myName)) instead.

Expression too complex error

I know this question gets asked quite a bit, but I haven't seen an answer that I can apply to my issue. It seems that this error can be caused by quite a few things.
First of all, here is the code:
SurfArea = 19.63495408
Volume = 12.2718463
DeSimpleFinal = 0.009336098
Counter = 13
pi = 4*atn(1)
tracker = 0
stepamount = (Range("A" & Counter + 1).Value) / 1000
If Range("XFD1048508").Value = 1 Then
For x = 0 To Range("A" & Counter + 1).Value Step Stepamount
tracker = tracker + 1
ActiveSheet.Range("XEY" & tracker).Value = ((2 * SurfArea) / Volume) * Sqr((DeSimpleFinal * x) / pi)
ActiveSheet.Range("XEX" & tracker).Value = x
Next
Else
End If
I've decided to leave (Range("A" & Counter + 1).Value) on, because I think it might be relevant to why the code is breaking down. That cell is A14 and has the value 11 inside of it.
The line that gets flagged when I debug is the first line of the For loop. The loop doesn't even go through one iteration.
Does anybody have an idea of what it could be? I changed all my data types to variant to see if that was the issue, but that did nothing. Thank you for your help!
EDIT: I should note that the value of that range SHOULD be one, so that it does go through the loop.
I don't know anywhere enough about VBA's internals to understand why, but I do know that simplifying the expression that sets the limit on a FOR loop will eliminate the Error 16 - Expression Too Complex problem. (The response to this SO post as well as discussion elsewhere on the web comes to pretty much the same conclusion.)
Just declare a new variable, say, StopAmount, assign to it the expression you used in the FOR condition, and then replace the expression in the FOR with the name of the new variable. You get something like:
StopAmount = Range("A" & Counter + 1).Value
......
For x = 0 To StopAmount Step Stepamount
......
That said, there are certainly some oddities here.
For example, your original FOR condition worked fine if the iterator variable x is declared as a Variant, either implicitly or explicitly. (I declared all the variables for my tests.)
However, if x is dimensioned as a Double, the error returned. This is despite the fact that TypeName(x) showed the Variant x as a Double after the Range(..).Value assignment is made.
For x = 0 To Range("A14").Value Step Stepamount also ran with no problem.
And For x = 0 To Cells(Counter + 1, 1).Value Step Stepamount worked, too.