VBA How do i split an integer into separate parts - vba

I'm working in VBA within Excel.
I need to split the integer into two parts, specifically the first two digits and the last two digits.
The numbers have a maximum of four digits and at least one. (I've already sorted out the blank values) eg.
7 should become 0 and 7,
23 should become 0 and 23,
642 should become 6 and 42,
1621 should become 16 and 21.
This is the code I have so far
Function Bloog(value1 As Integer)
Dim value1Hours, value1Mins As Integer
Select Case Len(value1) 'gives a number depending on the length of the value1
Case 1, 2 ' e.g., 2 = 0, 2 or 16 = 0, 16
value1Hours = 0
value1Mins = value1
Case 3 ' e.g., 735 = 7, 35
value1Hours = Left(value1, 1) ' 7
value1Mins = Right(value1, 2) ' 35
Case 4 ' e.g., 1234 = 12, 34
value1Hours = Left(value1, 2) ' 12
value1Mins = Right(value1, 2) ' 34
End Select
However when go to get the values i find that they have not been split up into the separate parts as the Left() and Right() function would have me believe.
Len() doesn't appear to be working either, when it was given the value 723 it returned a length of 2.
Any tips would be appreciated.
=======================================
After a suggestion I've cast the values as strings then done the case statement and converted them back afterwards. (because I need them for some calculations)
Private Function Bloog(value1 As Integer) As Integer
Dim strValue1 As String
Dim strValue1Hours, strValue1Mins As String
Dim value1Hours, value1Mins As Integer
'converts the values into strings for the Left() and Right() functions
strValue1 = CStr(value1)
Select Case Len(value1) 'gives a number depending on the length of the value1
Case 1, 2 ' e.g., 2 = 0, 2 or 16 = 0, 16
strValue1Hours = 0
strValue1Mins = value1
Case 3 ' e.g., 735 = 7, 35
strValue1Hours = Left(value1, 1) ' 7
strValue1Mins = Right(value1, 2) ' 35
Case 4 ' e.g., 1234 = 12, 34
strValue1Hours = Left(value1, 2) ' 12
strValue1Mins = Right(value1, 2) ' 34
End Select
value1Hours = CInt(strValue1Hours)
value1Mins = CInt(strValue1Mins)
Len() still believes that the length of the string is 2 and so case 2 statement was triggered, despite this the the strValue1Mins and the value1Mins still equals 832.
=======================
Len() was testing for Value1 not strValue1, everything works fine after that.

value1 is an integer, why not use arithmetic operations ?
Dim value1Hours as Integer,value1Mins as Integer
value1Mins = value1 Mod 100
value1Hours = Int(value1 / 100)

Hope this helps. This is the most simple way that I could think of.
ValueAsString = Right("0000" & value1,4)
strValue1Hours = Left(ValueAsString, 2)
strValue1Mins = Right(ValueAsString, 2)

For what it's worth:
value1Hours = CInt(Left(Format(x, "0000"), 2))
value1Mins = CInt(Right(Format(x, "0000"), 2))

Related

Label a set of objects with (A->Z,AA->ZZ, AAA->ZZZ) in VBA

I have a set which has an unknown number of objects. I want to associate a label to each one of these objects. Instead of labeling each object with a number I want to label them with letters.
For example the first object would be labeled A the second B and so on.
When I get to Z, the next object would be labeled AA
AZ? then BA, BB, BC.
ZZ? then AAA, AAB, AAC and so on.
I'm working using Mapbasic (similar to VBA), but I can't seem to wrap my head around a dynamic solution. My solution assumes that there will be a max number of objects that the set may or may not exceed.
label = pos1 & pos2
Once pos2 reaches ASCII "Z" then pos1 will be "A" and pos2 will be "A". However, if there is another object after "ZZ" this will fail.
How do I overcome this static solution?
Basically what I needed was a Base 26 Counter. The function takes a parameter like "A" or "AAA" and determines the next letter in the sequence.
Function IncrementAlpha(ByVal alpha As String) As String
Dim N As Integer
Dim num As Integer
Dim str As String
Do While Len(alpha)
num = num * 26 + (Asc(alpha) - Asc("A") + 1)
alpha = Mid$(alpha, 2,1)
Loop
N = num + 1
Do While N > 0
str = Chr$(Asc("A") + (N - 1) Mod 26) & str
N = (N - 1) \ 26
Loop
IncrementAlpha = str
End Function
If we need to convert numbers to a "letter format" where:
1 = A
26 = Z
27 = AA
702 = ZZ
703 = AAA etc
...and it needs to be in Excel VBA, then we're in luck. Excel's columns are "numbered" the same way!
Function numToLetters(num As Integer) As String
numToLetters = Split(Cells(1, num).Address(, 0), "$")(0)
End Function
Pass this function a number between 1 and 16384 and it will return a string between A and XFD.
Edit:
I guess I misread; you're not using Excel. If you're using VBA you should still be able to do this will the help of an reference to an Excel Object Library.
This should get you going in terms of the logic. Haven't tested it completely, but you should be able to work from here.
Public Function GenerateLabel(ByVal Number As Long) As String
Const TOKENS As String = "ZABCDEFGHIJKLMNOPQRSTUVWXY"
Dim i As Long
Dim j As Long
Dim Prev As String
j = 1
Prev = ""
Do While Number > 0
i = (Number Mod 26) + 1
GenerateLabel = Prev & Mid(TOKENS, i, 1)
Number = Number - 26
If j > 0 Then Prev = Mid(TOKENS, j + 1, 1)
j = j + Abs(Number Mod 26 = 0)
Loop
End Function

Automatic Calculation with given numbers

I would like to make CPU to calculate declared result from the given numbers that are also declared.
So far:
Dim ArrayOperators() As String = {"+", "-", "*", "/", "(", ")"}
Dim GlavniBroj As Integer = GBRnb() 'Number between 1 and 999 that CPU needs to get from the numbers given below:
Dim OsnovniBrojevi() As Integer = {OBRnb(), OBRnb(), OBRnb(), OBRnb()} '4 numbers from 1 to 9
Dim SrednjiBroj As Integer = SBRnb() '1 number, 10, 15 or 20 chosen randomly
Dim KrajnjiBroj As Integer = KBRnb() '25, 50, 75 or 100 are chosen randomly
Private Function GBRnb()
Randomize()
Dim value As Integer = CInt(Int((999 * Rnd()) + 1))
Return value
End Function
Private Function OBRnb()
Dim value As Integer = CInt(Int((9 * Rnd()) + 1))
Return value
End Function
Private Function SBRnb()
Dim value As Integer = CInt(Int((3 * Rnd()) + 1))
If value = 1 Then
Return 10
ElseIf value = 2 Then
Return 15
ElseIf value = 3 Then
Return 20
End If
Return 0
End Function
Private Function KBRnb()
Dim value As Integer = CInt(Int((4 * Rnd()) + 1))
If value = 1 Then
Return 25
ElseIf value = 2 Then
Return 50
ElseIf value = 3 Then
Return 75
ElseIf value = 4 Then
Return 100
End If
Return 0
End Function
Is there any way to make a program to calculate GlavniBroj(that is GBRnb declared) with the help of the other numbers (also without repeating), and with help of the given operators? Result should be displayed in the textbox, in a form of the whole procedure of how computer got that calculation with that numbers and operators. I tried to make it work by coding operations one by one, but that's a lot of writing... I'm not looking exactly for the code answer, but mainly for the coding algorithm. Any idea? Thanks! :)

Converting Numbers to Excel Letter Column vb.net

I am trying to write data to excel files using vb.net. So I my function which converts number column into excel letter columns.
Public Function ConvertToLetter(ByRef iCol As Integer) As String
Dim Reminder_Part As Integer = iCol Mod 26
Dim Integer_Part As Integer = Int(iCol / 26)
If Integer_Part = 0 Then
ConvertToLetter = Chr(Reminder_Part + 64)
ElseIf Integer_Part > 0 And Reminder_Part <> 0 Then
ConvertToLetter = Chr(Integer_Part + 64) + Chr(Reminder_Part + 64)
ElseIf Integer_Part > 0 And Reminder_Part = 0 Then
ConvertToLetter = Chr(Integer_Part * 26 + 64)
End If
End Function
The Function works ok with any other numbers.
For example,
1 => A
2 => B
...
26 => Z
27 => AA
...
51 => AY
52 => t (And here is when it start to went wrong) It is suppose to return AZ, but it returned t.
I couldn't figure out what part I made a mistake. Can someone help me or show me how to code a proper function of converting numbers to excel letter columns using vb.net.
This should do what you want.
Private Function GetExcelColumnName(columnNumber As Integer) As String
Dim dividend As Integer = columnNumber
Dim columnName As String = String.Empty
Dim modulo As Integer
While dividend > 0
modulo = (dividend - 1) Mod 26
columnName = Convert.ToChar(65 + modulo).ToString() & columnName
dividend = CInt((dividend - modulo) / 26)
End While
Return columnName
End Function
This will work up to 52.
Public Function ConvertToLetterA(ByRef iCol As Integer) As String
Select Case iCol
Case 1 To 26
Return Chr(iCol + 64)
Case 27 To 52
Return "A" & Chr(iCol - 26 + 64)
End Select
End Function
On a side note, you can write XLSX files directly with EPPlus via .Net. You can use letter notation for columns if you wish, or you can use numbers.
There are a couple flaws in the logic, the second else clause is not required and the operations should be zero based.
Public Function ConvertToLetter(ByRef iCol As Integer) As String
Dim col As Integer = iCol - 1
Dim Reminder_Part As Integer = col Mod 26
Dim Integer_Part As Integer = Int(col / 26)
If Integer_Part = 0 Then
ConvertToLetter = Chr(Reminder_Part + 65)
Else
ConvertToLetter = Chr(Integer_Part + 64) + Chr(Reminder_Part + 65)
End If
End Function

How to generate a 26-character hex string that equals to 106 bits and ((53 Ones - 53 Zeros) in binary)

I am looking for a way to generate a hexadecimal string that equals out to 106 bits, more specifically fifty three 1's and fifty three 0's after each hex char is converted to binary and added together. I'd like to keep it as random as possible considering the parameters of the request. How would I go about keeping an eye on the construction of the string so that it equals out the way I want?
For example:
(a8c05779f8934b14ce96f8aa93) =
(1010 1000 1100 0000 0101 0111 0111 1001 1111 1000 1001 0011 0100
1011 0001 0100 1100 1110 1001 0110 1111 1000 1010 1010 1001 0011)
One option is to create a list with an equal number of 0s and 1s and then sort it with an array of random keys:
Sub Main()
' Start with a list of 53 0's and 1's
Dim bitsList = New List(Of Integer)
For i = 1 To 53
bitsList.Add(1)
bitsList.Add(0)
Next
Dim bits = bitsList.ToArray()
' Create list of random keys
Dim keys = New List(Of Integer)
Dim rand = New Random()
For i = 1 To bits.Count
keys.Add(rand.Next())
Next
' Sort bits by random keys
Array.Sort(keys.ToArray(), bits)
' Create hex string
Dim s = ""
For i = 1 To bits.Length - 4 Step 4
Dim digit = bits(i + 3) * 8 + bits(i + 2) * 4 + bits(i + 1) * 2 + bits(i)
s = s + Hex(digit)
Next
Console.WriteLine(s)
End Sub
You can place 52 ones randomly in a 104 bit number by keeping track of how many ones has been placed already and calculate the probability that the next digit should be one. The first digit always has 1/2 probability (52/104), then the second digit has 51/103 or 52/103 probability depending on what the first digit was, and so on.
Put the bits in a buffer, and when it is full (four bits), that makes a hexadecimal digit that you can add to the string:
Dim rnd As New Random()
Dim bin As New StringBuilder()
Dim buf As Integer = 0, bufLen As Integer = 0, left As Integer = 52
For i As Integer = 104 To 1 Step -1
buf <<= 1
If rnd.Next(i) < left Then
buf += 1
left -= 1
End If
bufLen += 1
If bufLen = 4 Then
bin.Append("0123456789abcdef"(buf))
bufLen = 0
buf = 0
End If
Next
Dim b As String = bin.ToString()
To make a 106 bit value, change these lines:
Dim buf As Integer = 0, bufLen As Integer = 0, left As Integer = 53
For i As Integer = 106 To 1 Step -1
The resulting string is still 26 characters, the two extra bits are in the buf variable. It has a value between 0 and 3 that you can use to create the 27th character, however that is done.
To add a 22 bit hash to the string, you can use code like this:
bin.Append("048c"(buf))
Dim b As String = bin.ToString()
Dim m As New System.Security.Cryptography.SHA1Managed
Dim hash As Byte() = m.ComputeHash(Encoding.UTF8.GetBytes(b))
'replace first two bits in hash with bits from buf
hash(0) = CByte(hash(0) And &H3F Or (buf * 64))
'append 24 bits from hash
b = b.Substring(0, 26) + BitConverter.ToString(hash, 0, 3).Replace("-", String.Empty)

Generate random string in text field

We have that old software (made by one of the first employees many years ago) in company that uses Microsoft Access to run. Boss asked me to add a random string generation in the specific text box on click but i have no idea how to do that. I dont have any Microsoft Access programming experience, thats why i am askin you to help.
I managed to create button and text field so far. Thats where it stops. I also managed to access the code for the button action:
Private Sub command133_Click()
End Sub
This is one way, will work in Access VBA (which is an older basic than vb.net). It will generate a string with letters and numbers.
Sub test()
Dim s As String * 8 'fixed length string with 8 characters
Dim n As Integer
Dim ch As Integer 'the character
For n = 1 To Len(s) 'don't hardcode the length twice
Do
ch = Rnd() * 127 'This could be more efficient.
'48 is '0', 57 is '9', 65 is 'A', 90 is 'Z', 97 is 'a', 122 is 'z'.
Loop While ch < 48 Or ch > 57 And ch < 65 Or ch > 90 And ch < 97 Or ch > 122
Mid(s, n, 1) = Chr(ch) 'bit more efficient than concatenation
Next
Debug.Print s
End Sub
Try this function:
Public Function GetRandomString(ByVal iLength As Integer) As String
Dim sResult As String = ""
Dim rdm As New Random()
For i As Integer = 1 To iLength
sResult &= ChrW(rdm.Next(32, 126))
Next
Return sResult
End Function
Workin on #Bathsheba code, I did this. It will generate a random string with the number of characters you'd like.
Code :
Public Function GenerateUniqueSequence(numberOfCharacters As Integer) As String
Dim random As String ' * 8 'fixed length string with 8 characters
Dim j As Integer
Dim ch As Integer ' each character
random = ""
For j = 1 To numberOfCharacters
random = random & GenerateRandomAlphaNumericCharacter
Next
GenerateUniqueSequence = random
End Function
Public Function GenerateRandomAlphaNumericCharacter() As String
'Numbers : 48 is '0', 57 is '9'
'LETTERS : 65 is 'A', 90 is 'Z'
'letters : 97 is 'a', 122 is 'z'
GenerateRandomAlphaNumericCharacter = ""
Dim i As Integer
Randomize
i = (Rnd() * 2) + 1 'One chance out of 3 to choose one of 3 catégories
Randomize
Select Case i
Case 1 'Numbers
GenerateRandomAlphaNumericCharacter = Chr(Rnd() * 9 + 48)
Case 2 'LETTERS
GenerateRandomAlphaNumericCharacter = Chr(Rnd() * 25 + 65)
Case 3 'letters
GenerateRandomAlphaNumericCharacter = Chr(Rnd() * 25 + 97)
End Select
End Function
I use it with random number of characters, like this :
'Generates random Session ID between 15 and 30 alphanumeric characters
SessionID = GenerateUniqueSequence(Rnd * 15 + 15)
Result :
s8a8qWOmoDvC4jKRjPr5hOY12u 26
TB24qZ4cNfr6EdyY0J 18
6LZRQ9P5WHLNd71LIdqJ 20
KPN0RmlhhJKnVzPTkW 18
R2pNOKWJMKl9KpSoIV2egUNTEb1QC2 30
X8jHuupP6SvEI8Dt2wJi 20
NOTE: This is still not completely random. It will give a higher count of numbers than normal as approx 1/3 of all chars generated will be numbers.
Normally distribution will look like:
10 numbers plus 26 lowercase plus 26 uppercase = 62 possible chars.
Numbers will normally be 10/62 parts of the string or 1/6.2
With the code
i = (Rnd() * 2) + 1 'One chance out of 3 to choose one of 3 catégories
the count of numbers is pushed up to 1/3 (on average)
Probably not too much of a worry - unless you are trying to beat the NSA and then you have decreased your range significantly.