How do I get VBA to recognize "001" for my loop? - string

I'm making a basic loop as follows:
Sub IntegerTestforSuffixFinder()
Dim i As Double
i = 1
MsgBox (i)
Do While i < 100
i = i + 1
If vbOK Then
MsgBox (i)
Else: End
End If
Loop
End Sub
This works just fine...but would I really need it to do for the actual problem I'm about to tackle is recognize i = 001. The zeroes are important place holders in this context, but it keeps correcting me to i = 1. Is there a way to stop this?
Much thanks!

You wouldn't. And you can't. But you can use the original Integer in your loop, and create a string that you can display. Try this and see if you can pull what you need from it:
Sub IntegerTestforSuffixFinder()
Dim i As Double
i = 1
MsgBox (i)
Do While i < 100
i = i + 1
If vbOK Then
'Original integer
MsgBox (i)
'3-character string created by using the Right() function
MsgBox Right("000" & i, 3)
Else: End
End If
Loop
End Sub
BTW, in your original example you realize you're starting your MsgBox at 2? You set i = 1, then you're adding 1 to it before displaying the first MsgBox. I'm thinking you probably want to move that i = i + 1 line to just before the Loop.

Try this:
Format cell - Custom. Look for Type with a "0". Type three "0" as below:
The value remains as integer.

Related

Setting up repeat action. Am lost if its a Loop or Do or ? Statement

'I need this to repeat the copy and paste process across columns until counter
'= either key page, "book" cell or reads from row 1, if row 1# = key"book"#
'Next column(Page) should be 3columns from last copy/Pasted column
"PicPg" B2 copies to "PrntPg" B2
E2 to E2
etc
**This is my very first post in any forum to ask for help. Forgive the ignorance.
I'll try and answer any questions the best I can.
Thank you in advanced for your time and help!
I can share the workbook, just not sure how.
Sub createPrintPage()
With Worksheets("PicPg").Cells(2, 2)
.Copy
Sheets("PrntPg").Pictures.Paste(Link:=True).Select
With Worksheets("PrntPg").Cells(2, 5)
.Select
Worksheets("PicPg").Cells(2, 5).Copy
Sheets("PrntPg").Pictures.Paste(Link:=True).Select
End With
End With
End Sub
'the "For i", I have not figured out yet. I have been trying to get it to
'continue repeating.... I've tried to play with for i's... I get lost
'this with statement seems to be working, now to get it to continue across.
'this is day 3 ive researched, Tried many ways... and can only get this far (and this
'is much MUCH prettier(ie:Simplier) then where I began.
both method is used to loop and iterate. if you want to use For just give it a beginning and an ending
Dim i As Integer
For i = 0 To 3
'put your code in here and it will loop 4x (i = 0, i = 1, i = 2 and i = 3)
Next i
'you can put your condition for the loop to exit either at the Do or Loop by using until
i = 0
Do Until i = 3
'although start from 0, but it will loop 3x because when it hit i = 3 it will stop (i = 0, i = 1, i = 2 and i = 3)
i = i + 1 'remember to increment your counter, before leaving the loop the counter had changed to 1
Loop
i = 0
Do
'although start from 0, but it will loop 3x because when it hit i = 3 it will stop (i = 0, i = 1, i = 2 and i = 3)
i = i + 1 'remember to increment your counter
Loop Until i = 3
there is also a lot more different ways to write it.
you can use cell iteration to do your loop
Dim cell As Object 'late binding, early binding can write Dim cell as range
For Each cell In ThisWorkbook.Range("A1:A20")
'do something
Next cell
you can even use your own condition to set the stop
Do
If x = 1 Then
ThisWorkbook.Range("A1").Value = "True"
End If
Loop Until ThisWorkbook.Range("A1") = "True"
you can even Exit Do or Exit For if you have already achieved your desired outcome.
Dim i as Integer, temp as string
For i = 0 To 3
If ThisWorkbook.Range("A" & i).Value2 = "True" Then
temp = "hey, I found what I am looking for"
Exit For
End If
Next i

Report Date as String won't convert to Long

I've been banging my head on this issue! I have a variable called repDate which today is equal to "5/1/2020" as a string. I've tried this formula to convert it to a Long so I can compare it to a date in the file rDtLng = CLng(repDate). I'm getting error "Type Mismatch" which I am not sure why there would be one. This is where I am doing the comparing the rest works great, just the report date as long doesn't want to work.
'repDate equals "5/1/2020", currently
rDtLng = CLng(repDate)
.
.
.
'Delete charge offs
For w = rwCnt To 3 Step -1
Do While .Cells(w, napbRng.Column).Value2 <= 0 And .Cells(w, apbRng.Column).Value2 <= 0
If .Cells(w, matDtRng.Column).Value2 = "" Then Exit Do
If .Cells(w, matDtRng.Column).Value2 < rDtLng Then
.Rows(w).Delete shift:=xlShiftUp
Else: Exit Do
End If
Loop
Next w
Thanks in advance!
CLng expects a numeric input, which the text-that-looks-like-a-date "5/1/2020" is not.
You can convert that to an actual date using CDate and then perform mathematical operations on it, including the existing < comparison.
Though if I understand what your end goal is, you might consider Range.AutoFilter with a date filter, and then deleting visible rows, instead of your current Do loop approach.
Side note: you could CLng(CDate("5/1/2020")) and the result would be 43952, but that's an unnecessary step, as you can do math with dates directly.
Use DateValue() Function.
Sub test()
Dim myDate As Long
Dim str As String
str = "5/1/2020"
myDate = DateValue(str)
If myDate = DateSerial(2020, 5, 1) Then
MsgBox "OK"
End If
End Sub

Excel VBA Return Row number/index from Range("rngNme").Columns(n).Cells

I want to produce a mini report of several items matching a key. In my loop I get the keys returned but can't fathom out how I can access the data that I need in the report that is held in other columns.
I put in some msgbox's to trap the data and an escape mechanism to get out of the loop. These I have commented out below as well as the data lines that don't work. "cbdata" is a workbook named range covering B5:T4019. The report is being compiled on a different sheet (activesheet). For some unknown reason on looping through without outputing any data "r" gets updated to some spurious numbers like 2421 (first loop) this appears to be linked somehow to the data in "cbdata". The first entry is actually in row 2388 so it doesn't really correlate to an indexed row in the range. However, I think first of all I need to find out what I can do to get the corresponding row returned for each of my passes. "ky" returns all the entries in columns(19) but I'm only interested in those that match "ledcdeyr" which in this instance is "2012017" that bit works returning all the entries matching in the loop.
Having got the key information agreeing, how might I relate this to the row number so that I can extract the other data from that row.
(cr is vbcrlf)(r should be the row number of the receiving report)
Any pointers would be greatly appreciated.
Code:
r = r + 1 ' row 38 when entering process
For Each ky In Range("cbdata").Columns(19).Cells
'ans = MsgBox(ky & cr & r, vbOKCancel)
'If ans = vbCancel Then Exit Sub
If ky = ledcdeyr Then
ans = MsgBox(ky & cr & r, vbOKCancel)
If ans = vbCancel Then Exit Sub
Cells(r, 2) = Range("cbdata").Cells(ky, 1)
'Cells(r, 3) = Range("cbdata").Columns(2).Cells
'Cells(r, 4) = Range("cbdata").Columns(3).Cells
'Cells(r, 5) = Range("cbdata").Columns(4).Cells
'Cells(r, 6) = Range("cbdata").Columns(5).Cells
ans = MsgBox(r, vbOKCancel + vbQuestion, title)
If ans = vbCancel Then Exit Sub
End If
r = r + 1
Next
I am not entirely sure I follow but the Range object during the loop is ky. The row for that cell be retrieved with .Row property
ky.Row
Somewhat random example with a conditional test:
Option Explicit
Public Sub Test()
Dim ky As Range, counter As Long
Dim loopRange As Range
Set loopRange = ThisWorkbook.Worksheets("Sheet1").Range("cbdata").Columns(19)
For Each ky In loopRange.Cells
counter = counter + 1
If ky = 1 Then
Debug.Print ky.Row, counter
Debug.Print loopRange(counter).Address
End If
Next
End Sub
I ran the undernoted slightly amended code on my project but it produced some spurious results.
I had already tried the ky.row but when it didn't give me the information, I just thought that it wasn't the answer.
Public Sub Test()
Dim ky As Range, counter As Long
Dim loopRange As Range
'Set loopRange = ThisWorkbook.Worksheets("Sheet1").Range("cbdata").Columns(19)
Set loopRange = Range("cbdata").Columns(19) ' workbook range name
For Each ky In loopRange.Cells
counter = counter + 1
'ans = MsgBox(counter & vbCrLf & ky & vbCrLf & ky.Row, vbOKCancel)
'If ans = vbCancel Then Exit Sub
If ky = 2012017 Then
Debug.Print ky.Row, counter
Debug.Print loopRange(counter).Address
End If
Next
End Sub
The Debug results from running the above code for the first 4 records were:
2388 2384
$CNK$5:$CNK$4091
2408 2404
$COE$5:$COE$4091
2444 2440
$CPO$5:$CPO$4091
2450 2446
$CPU$5:$CPU$4091
The numbers on the left produced by ky.row are correct. The numbers on the right relate somehow to the counter which here should be 1, 2, 3, 4. This is the same situation that occurred with my "r" and hence didn't produce the information where I expected to see it. Which caused me to think that ky.row was not working. Also my range "cbdata" is B5:T4091 The rows are correct but the "CNK" etc - I don't know where that has come from.
I thought I'd just feed back to you where I'm at and your reply certainly made me look further, as I seemed to be going round in circles.
If you have any idea how the counter would be acting so spuriously then perhaps you could let me know. Having used your code on its own the that clears up any issue with there not being a problem with any other part of my code. Thanks again.

Excel says no "End Sub", and crashes just by moving cursor

I am writing a VBA code to go through a specified range or ranges, look for a keyword provided by the user at run-time, and grab the value in the cell offset from the cell with the keyword by an amount also provided by the user. For instance, if you wanted to look through A1:B10 for the word "Apple" and then grab the value in the cell to the right of every instance of "Apple", it can do that. Two weird things have been occurring for me. First and not so weird, when I run it and click the cancel button on the userform that only contains the single line "Unload Me", it throws an error saying it expected and End Sub statement, but it has one. I don't know why it is doing that. Weird thing number 2. Whenever I click and move the cursor to the end of the file after the Cancel_Click() sub, my excel crashes and closes. Every. Single. Time. And it is weird that it does that just from me clicking. It also sometimes happens when I click around the Cancel_Click() sub or hit enter around there too. Just simply from clicking. I don't get it. Any ideas? Code contained in the userform is below. Fyi, the user can input ranges like "A1:A10,E1:E10" separated by commas for multiple ranges. I don't think it is important for this question, but I thought I would add that since i don't know how to add the userform here, if you even can.
Private Sub Accept_Click()
'Searches for string input into the KeywordBox
'Grabs contents of the cell defined by the OffsetBox
'The range it searches through is defined by the RangeBox
Dim rawRange As String: rawRange = Me.RangeBox.Text
Dim rawOffset As String: rawOffset = Me.OffsetBox.Text
Dim Keyword As String: Keyword = Me.KeywordBox.Text
Dim numOfRanges As Integer: numOfRanges = 1
Dim Ranges() As Range
Dim commaLoc As Integer: commaLoc = -1
Dim tempRange As String: tempRange = rawRange
Dim offset As Integer
Dim values() As Double
Dim valCount As Integer: valCount = 0
'--------------------------------------------------------
'Set ranges
For i = 1 To Len(rawRange)
If (Mid(rawRange, i, 1) = ",") Then
numOfRanges = numOfRanges + 1
End If
Next
ReDim Ranges(numOfRanges) As Range
If (Not numOfRanges = 1) Then
For i = 1 To numOfRanges - 1
commaLoc = InStr(1, tempRange, ",")
Set Ranges(i) = Range(Left(tempRange, commaLoc - 1))
tempRange = Right(tempRange, Len(tempRange) - commaLoc)
Next
End If
Set Ranges(numOfRanges) = Range(tempRange)
'---------------------------------------------------------
'Set offset
If (IsNumeric(rawOffset)) Then
offset = CInt(rawOffset)
Else:
MsgBox ("Offset was not input as a number")
Exit Sub
End If
'----------------------------------------------------------
'Searches for keyword
For i = 1 To numOfRanges
For Each cell In Ranges(i)
If (cell.Value = Keyword) Then
valCount = valCount + 1
End If
Next
Next
ReDim values(valCount) As Double
valCount = 0
For i = 1 To numOfRanges
For Each cell In Ranges(i)
If (cell.Value = Keyword) Then
valCount = valCount + 1
values(valCount) = cell.offset(0, offset).Value
End If
Next
Next
For i = 1 To valCount
Range("I" & i).Value = values(i)
Next
Unload Me
End Sub
I've had similar, weird things happen to me. A good thing to try is to force the VBA project to reset, then save, exit, and restart Excel.
To force a project reset, add an Enum to the general section of one of your code modules. It doesn't matter what the enum is...make it something simple, like
Enum stoplight
Red
Yellow
Green
End Enum
As you do that, you'll get a message saying that it will reset your project. That's fine; let that happen. Then save your Excel workbook, exit excel completely, start it up again, reload your workbook, go into the VBA Editor, and delete the enum you added. Then recompile and see if things work better for you.
You put an "Exit Sub" in the set offset, this is probably causing your problem.
I was able to fix the issue by making a new workbook and copying everything over. It worked fine. I think the original was corrupted somehow. For those having the same issue, I think Rich Holton's answer would be worth a try in case you have more than just a few things to copy. Thanks everyone for you time and input on this!

Excel VBA offset Copy Paste

Hope you're doing well. I'm going to preface this by saying I'm not a programmer and I'm sure the code I have started is riddled with more errors then what I think. Hopefully you can help :D.
I have an Excel sheet that gets generated from another program that comes out like this:
excel sheet
However, the size of this sheet can change with every new generation of this sheet from the other program. (ex, A can have 7 next time, and D could have 9) And the sheet as it is cannot be used easily to do the math required as I only need specific groups of information at a given time, in this example groups B and D only.
What I'm hoping to create is something that will take the sheet as its generated, and turn it into something that looks like this:
result sheet
This is the code I've written so far, but since I don't really know what I'm doing I keep running into numerous problems. Any help would be appreciated.
Option Explicit
Sub Numbers()
Dim matchesFound As Integer
Dim row As Integer
Dim c As Integer
Dim copyRow As Integer
Dim copyLocationColumn As Integer
Dim arr(2) As String
arr(0) = "1"
arr(1) = "2"
arr(2) = "3"
Function arrayContainsValue(array, varValue)
found = false
for each = 0 to array
if array(i) = varValue then
found = true
exit for
arrayContainsValue = found
End Function
row = 1
c = 1
copyLocationColumn = 1
copyRow = 1
matchesFound = 0
Do While matchesFound < 3
if arrayContainsValue(arr, ThisWorkbook.Sheets("Data").Cell(column,row))
matchesFound = matchesFound + 1
Do While ThisWorkbook.Sheets("Data").Cell(column, row)
ThisWorkbook.Sheets("postHere").Cell(copyLocationColumn, copyRow) = _
ThisWorkbook.Sheets("postHere").Cell(c + 1, row)
copyRow = copyRow+1
row = row + 1
Loop
End If
row = row + 1
Loop
End Sub
There are many logic errors to numerate in a comment, Excel highlights them automatically I'll do a summary explaining them:
1. Function can't be "in the middle" of the sub, finish the Sub (take the Function from the sub and paste until it says end sub.
2.array is a forbidden name, try with another variable name
3.For each =0 ? to array? what do you try to mean like that? For Each has to be element in something For each element in Array for example For and To are for something defined in numbers (for counter=1 to 15)
Function arrayContainsValue(***array***, varValue) '2nd problem
found = false
for each = 0 to array '3rd problem
if array(i) = varValue then
found = true
exit for
arrayContainsValue = found
End Function
....
4. you're missing a then at the end
if arrayContainsValue(arr, ThisWorkbook.Sheets("Data").Cell(column,row))
I don't get the coding logic on how relates to the problem stated (?)

Resources