I need my code to return the randomized string and its returning nothing. Ive included the code to make it easier. I hope this helps.
Everything is running and the msg is coming up but variables dna1 and dna2 are empty.
Dim lengthDNA As Integer
Sub dna()
Dim str As String, dna1 As String, dna2 As String
Dim x As Long
lengthDNA = InputBox("Enter the length of DNA sequences (10-250)")
dna1 = RandInteger("ACGT")
dna2 = RandInteger("ACGT")
MsgBox ("DNA Sequence 1 is: " & dna1 & Chr(13) & "DNA Sequence 2 is: " & dna2), vbInformation
End Sub
Public Function RandInteger(strRandom As String) As String
dnaBank = Array("A", "C", "G", "T")
For x = 1 To lengthDNA
Randomize
strRandom = strRandom & dnaBank(Int((UBound(dnaBank) - LBound(dnaBank) 1) * Rnd LBound(dnaBank)))
Next x
End Function
CodePudding user response:
No return value is ever specified for RandInteger
.
Add RandInteger = strRandom
as the last statement of the function..
Note
You might also want to check other portions of the code:
- It does not make much sense to pass a fixed prefix string to the randomizer function. Instead make the target length of the random string a parameter.
Randomize
initializes VBAs random number generator. It should be called once for the whole program instead of before every call toRnd
as it is now.
CodePudding user response:
Don't use global variables if you don't need to. Declare your variables as local as possible and as close tho their first use as possible. If you need ot submit a variable to another function/sub submit it as parameter.
Option Explicit
Public Sub dna()
Dim lengthDNA As Long
' get DNA length from user input, allow user to press cancel
Dim ReturnValue As Variant
ReturnValue = Application.InputBox(Prompt:="Enter the length of DNA sequences (10-250)", Type:=1) 'Type:=1 Allow numbers only
If VarType(ReturnValue) = vbBoolean And ReturnValue = False Then
'user pressed cancel
Exit Sub
Else
lengthDNA = ReturnValue
End If
Dim dna1 As String
dna1 = CreateRandomDNA(lengthDNA)
Dim dna2 As String
dna2 = CreateRandomDNA(lengthDNA)
MsgBox "DNA Sequence 1 is: " & dna1 & Chr(13) & "DNA Sequence 2 is: " & dna2, vbInformation
End Sub
Public Function CreateRandomDNA(ByVal Length As Long) As String
Dim dnaBank As Variant
dnaBank = Array("A", "C", "G", "T")
Randomize
Dim strRandom As String
Dim x As Long
For x = 1 To Length
strRandom = strRandom & dnaBank(Int((UBound(dnaBank) - LBound(dnaBank) 1) * Rnd LBound(dnaBank)))
Next x
CreateRandomDNA = strRandom ' return random string to function
End Function