VBA Error: "The object invoked has disconnected from its clients" - vba

I am attempting to write a macro that matches up x/y coordinates to ellipses that they fit into. I get the automation error at the "Else" line in my code. I have reviewed a lot of other posts but I can't figure out what is wrong with my code. Any assistance is much appreciated. Thank you!
Private Sub CommandButton1_Click()
Dim XR As Integer
Dim XC As Integer
Dim YR As Integer
Dim YC As Integer
Dim areaR As Integer
Dim areaC As Integer
Dim hR As Integer
Dim hC As Integer
Dim kR As Integer
Dim kC As Integer
Dim aR As Integer
Dim aC As Integer
Dim bR As Integer
Dim bC As Integer
Dim angleR As Integer
Dim angleC As Integer
Dim matchR As Integer
Dim matchC As Integer
XR = 2
XC = 1
YR = 2
YC = 2
Do Until ThisWorkbook.Sheets("Sheet1").Cells(XR, XC).Value = ""
ThisWorkbook.Sheets("Sheet1").Activate
areaR = 2
areaC = 6
hR = 2
hC = 7
kR = 2
kC = 8
aR = 2
aC = 9
bR = 2
bC = 10
angleR = 2
angleC = 11
matchR = XR
matchC = 12
Do Until ThisWorkbook.Sheets("Sheet1").Cells(hR, hC).Value = ""
If (((((ThisWorkbook.Sheets("Sheet1").Cells(XR, XC).Value) _
- (ThisWorkbook.Sheets("Sheet1").Cells(hR, hC).Value)) * _
Cos((ThisWorkbook.Sheets("Sheet1").Cells(angleR, angleC).Value)) _
+ ((ThisWorkbook.Sheets("Sheet1").Cells(YR, YC).Value) - _
(ThisWorkbook.Sheets("Sheet1").Cells(kR, kC).Value)) * Sin _
((ThisWorkbook.Sheets("Sheet1").Cells(angleR, angleC).Value))) ^ 2) _
/ ((Cells(aR, aC).Value) ^ 2)) + (((((Cells(XR, XC).Value) - _
(Cells(hR, hC).Value)) * Sin((ThisWorkbook.Sheets("Sheet1").Cells _
(angleR, angleC).Value)) - ((ThisWorkbook.Sheets("Sheet1").Cells(YR, YC).Value) _
- (ThisWorkbook.Sheets("Sheet1").Cells(kR, kC).Value)) _
* Cos((Cells(angleR, angleC).Value))) ^ 2) / ((Cells(bR, bC).Value) ^ 2)) _
<= 1 Then
ThisWorkbook.Sheets("Sheet1").Cells(matchR, matchC).Value = _
ThisWorkbook.Sheets("Sheet1").Cells(areaR, areaC)
Else
areaR = areaR + 1
hR = hR + 1
kR = kR + 1
aR = aR + 1
bR = bR + 1
angleR = angleR + 1
End If
Loop
XR = XR + 1
YR = YR + 1
Loop
End Sub

That's a lot of code, and doing direct math with cell reference values is very hard to read...probably even for you.
It may not be much of an answer, but if you create variables (yes, more variables), inside your loops, then your code will be easier to read for everyone and very possibly your error will emerge.
So instead of using ThisWorkbook.Sheets("Sheet1").Cells(XR, XC).Value in your calculation, first do this: X = ThisWorkbook.Sheets("Sheet1").Cells(XR, XC).Value
But don't stop there. Include intermediate variable that will self-describe your code and the calculation process.
This will hopefully allow you to see the code for what it really does.
isMatch = cosX <= 1
If isMatch Then
And, by the way, my suspission is that your error is coming from the fact that you are not qualifying all of your Cells methods with a sheets reference.

Related

I have problem that says System.Security.Cryptography.CryptographicException: 'Bad Data. ' in vb.net when trying to import RSA parameters

Here's the code I am not sure if there's any hidden error but on runtime when trying to import the rsa parameters it pops up that error
Imports System.Security.Cryptography
Imports System.Security
Imports System.Text
Imports System.IO
Public Class RSA_Test_Form
Public FactorList As New List(Of Integer)
Public FindFactor As Long
Public PString, QString, ModulusString, ExponentString, DString, DPString,
DQString, InverseQString As String
Function ModInverse(ByVal a As Long, ByVal b As Long) As Long
Dim b0 As Long = b
Dim t As Long
Dim q As Long
Dim x0 As Long = 0
Dim x1 As Long = 1
If b = 1 Then Return 1
While a > 1
q = a \ b
t = b
b = a Mod b
a = t
t = x0
x0 = x1 - q * x0
x1 = t
End While
If x1 < 0 Then x1 += b0
Return x1
End Function
Function gcd(ByVal n1 As Long, ByVal n2 As Long) As Long
Dim i As Integer
Dim minimum As Integer
If n1 < n2 Then
minimum = n1
Else
minimum = n2
End If
For i = minimum To 1 Step -1
If n1 Mod i = 0 And n2 Mod i = 0 Then
Return i
End If
Next
Return gcd
End Function
Sub FindFactorFunction()
Dim x As Long
For x = 2 To FindFactor - 1
If FindFactor Mod x = 0 Then
FactorList.Add(x)
End If
Next
End Sub
Private Sub GenerateBTN_Click(sender As Object, e As EventArgs) Handles GenerateBTN.Click
Dim Result As Long = 0
Dim Result2 As Long = 0
Dim Result3 As Long = 0
Dim Random1, Random2 As New Random()
Dim P, Q, Modulus As Long
Dim Exponent, D, DP, DQ As New Nullable(Of Long)
Dim InverseQ As New Nullable(Of ULong)
Dim Modulus1 As Long = 0
Dim LoopCount As Integer = 0
Dim ls, ls2 As New List(Of Long)
Dim PrimeString As String
PrimeString = ""
Using MyNewStreamReader As StreamReader = New StreamReader("AllPrimes.txt")
PrimeString = MyNewStreamReader.ReadLine().ToString
MessageBox.Show(PrimeString)
While PrimeString <> "" And LoopCount <= 1249
ls.Add(Long.Parse(PrimeString))
LoopCount += 1
PrimeString = ""
PrimeString = MyNewStreamReader.ReadLine
End While
End Using
Using MyNewStreamReader2 As StreamReader = New StreamReader("AllPrimes.txt")
PrimeString = ""
PrimeString = MyNewStreamReader2.ReadLine().ToString
LoopCount = 0
MessageBox.Show(PrimeString)
While PrimeString <> ""
If LoopCount >= 1250 And LoopCount <= 2499 Then
ls2.Add(Long.Parse(PrimeString))
End If
LoopCount += 1
PrimeString = ""
PrimeString = MyNewStreamReader2.ReadLine
End While
End Using
Dim rand = Random1.Next(0, ls.Count)
Dim rand2 = Random2.Next(0, ls2.Count)
P = ls(rand)
Q = ls2(rand2)
Result3 = gcd(P, Q)
While Result3 <> 1
rand = Random1.Next(0, ls.Count)
rand2 = Random2.Next(0, ls2.Count)
P = ls(rand)
Q = ls2(rand2)
Result3 = gcd(P, Q)
End While
MessageBox.Show("P= " & P & "Q= " & Q)
Modulus = (P - 1) * (Q - 1)
Modulus1 = Modulus + 1
FindFactor = Modulus1
FindFactorFunction()
Dim Count As Integer = 0
Dim Count2 As Integer = 0
For A As Integer = 0 To FactorList.Count - 1
Result = gcd(FactorList.ElementAt(A), Modulus)
If Result = 1 Then
Count += 1
End If
Next
Dim PositionArray(Count) As Integer
Count = 0
For A As Integer = 0 To FactorList.Count - 1
Result = gcd(FactorList.ElementAt(A), Modulus)
If Result = 1 Then
PositionArray(Count) = FactorList.ElementAt(A)
Count += 1
End If
Next
Dim Number1, Number2 As Long
Dim GetResult As Boolean = False
Count = 0
If PositionArray.Count = 2 Then
Exponent = PositionArray(0)
D = PositionArray(1)
Else
While GetResult = False And Count <> PositionArray.Count
For Count = 0 To PositionArray.Count - 1
For Count2 = Count + 1 To PositionArray.Count - 1
Number1 = PositionArray(Count)
Number2 = PositionArray(Count2)
Result2 = Number1 * Number2 Mod Modulus
If Result2 = 1 Then
GetResult = True
End If
If GetResult = True Then
Exit While
End If
Next
Next
End While
End If
Dim Selection As Integer = MessageBox.Show(Number1 & "=E And D= " & Number2, "Information", MessageBoxButtons.OKCancel, MessageBoxIcon.Information)
If Selection = DialogResult.OK Then
Exponent = Number1
D = Number2
DP = D * P
DQ = D * Q
InverseQ = ModInverse(Q, P)
MessageBox.Show("DP= " & DP)
MessageBox.Show("DQ= " & DQ)
MessageBox.Show("InverseQ= " & InverseQ)
In here when generating RSA numbers, I can not always get the correct numbers so i am using this website to check that i have get the correct RSA numbers and the D and Exponent was not = 0
Exponent=e
Everytime I get Exponent and D, I will always use this website to check P,Q,Exponent and D to make sure it's correct
https://www.cs.drexel.edu/~jpopyack/IntroCS/HW/RSAWorksheet.html
End If
If Exponent.HasValue And D.HasValue Then
PString = P.ToString
QString = Q.ToString
ModulusString = Modulus.ToString
ExponentString = Exponent.ToString
DString = D.ToString
DPString = DP.ToString
DQString = DQ.ToString
InverseQString = InverseQ.ToString
In here all D,P,Q,DP,DQ,Exponent,Modulus,InverseQ value has been calculated and checked
End If
End Sub
Private Sub Number2ByteConverterBTN_Click(sender As Object, e As EventArgs) Handles Number2ByteConverterBTN.Click
If it's possible try check the coding here, perhaps this place was the place that i do it wrongly
I initially thought of using BitCoverter.GetBytes() to convert the long and Ulong datatype value
But in the end, the bitconverter.getbytes() doesn't work for me so i have to first convert all those long and ulong data type values into string then use BYTE.PARSE() to convert the string into byte value
That's how i do it
If let's any experts here confirmed that the coding above worked and all the values are correct then try to check is there any potential error here
Dim PByte, QByte, ModulusByte, ExponentByte, DByte, DPByte, DQByte, InverseQByte As Byte()
ReDim PByte(PString.Count)
ReDim QByte(QString.Count)
ReDim ModulusByte(ModulusString.Count)
ReDim ExponentByte(ExponentString.Count)
ReDim DByte(DString.Count)
ReDim DPByte(DPString.Count)
ReDim DQByte(DQString.Count)
ReDim InverseQByte(InverseQString.Count)
Dim TempPByte, TempQByte, TempModulusByte, TempExponentByte, TempDByte As New Byte
Dim StringBuilder As New StringBuilder
Dim StringBuilder2 As New StringBuilder
Dim StringBuilder3 As New StringBuilder
Dim StringBuilder4 As New StringBuilder
Dim StringBuilder5 As New StringBuilder
Dim StringBuilder6 As New StringBuilder
Dim StringBuilder7 As New StringBuilder
Dim StringBuilder8 As New StringBuilder
For i As Integer = 0 To PString.Length - 1
PByte(i) = Byte.Parse(PString.ElementAt(i))
StringBuilder.Append(PByte(i).ToString)
Next
For i As Integer = 0 To QString.Length - 1
QByte(i) = Byte.Parse(QString.ElementAt(i))
StringBuilder2.Append(QByte(i).ToString)
Next
For i As Integer = 0 To ModulusString.Length - 1
ModulusByte(i) = Byte.Parse(ModulusString.ElementAt(i))
StringBuilder3.Append(ModulusByte(i).ToString)
Next
For i As Integer = 0 To ExponentString.Length - 1
ExponentByte(i) = Byte.Parse(ExponentString.ElementAt(i))
StringBuilder4.Append(ExponentByte(i).ToString)
Next
For i As Integer = 0 To DString.Length - 1
DByte(i) = Byte.Parse(DString.ElementAt(i))
StringBuilder5.Append(DByte(i).ToString)
Next
For i As Integer = 0 To DPString.Length - 1
DPByte(i) = Byte.Parse(DPString.ElementAt(i))
StringBuilder6.Append(DPByte(i).ToString)
Next
For i As Integer = 0 To DQString.Length - 1
DQByte(i) = Byte.Parse(DQString.ElementAt(i))
StringBuilder7.Append(DQByte(i).ToString)
Next
For i As Integer = 0 To InverseQString.Length - 1
InverseQByte(i) = Byte.Parse(InverseQString.ElementAt(i))
StringBuilder8.Append(InverseQByte(i).ToString)
Next
Dim MyRSAParams As New RSAParameters
MyRSAParams.P = PByte
MyRSAParams.Q = QByte
MyRSAParams.Exponent = ExponentByte
MyRSAParams.Modulus = ModulusByte
MyRSAParams.D = DByte
MyRSAParams.DP = DPByte
MyRSAParams.DQ = DQByte
MyRSAParams.InverseQ = InverseQByte
Dim MyRSA As RSA
MyRSA = RSA.Create()
MyRSA.ImportParameters(MyRSAParams)
End Sub
Private Sub RSA_Test_Form_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim temp, temp2 As Integer
temp = gcd(1, 2)
temp2 = gcd(2, 3)
FindFactor = 0
End Sub
End Class
What I am trying to do in the generate button was to create the suitable parameters for RSA.
The parameters I was actually able to generate them but in either ULong or Long data type.
When i first convert them into array of Bytes I have considered to use BitConverter but it doesn't work at least in my case.
The only way i am only able to make them into array of Bytes was by making the ULong or Long data type variable into string.
Then convert those string into Byte then put them into ByteArray
I hope it was correct but it is out of my reach for now.
Any ideas on how can i make the parameter data to be accepted as rsa parameter?

What is different between Microsoft.VisualBasic.VBMath.Rnd and the old VB Rnd() function?

I am trying to convert some old VB code to .Net but am having a problem with the Rnd function.
Old Code
Private Function Decode() As String
Dim r As Integer
Dim x As Integer
Dim c As Integer
Dom Code As String = "m[n-Msr0Xn*ca8qiGeIL""7'&;,_*EV{M;[{2bEmg8u!^s*+O37!692{-Y4IS"
x = Int(Rnd(-7))
For r = 1 To Len(Code)
x = Int(Rnd() * 96)
c = Asc(Mid(Code, r, 1))
c = c + x
If c >= 126 Then c = c - 126 + 32
Decode = Decode & Chr$(c)
Next
End Function
The decoded text is "Bet you needed more than a pencil and paper to get this one!"
This is what I have done:
Private Function Decode() As String
Dim r As Integer
Dim x As Integer
Dim c As Integer
Dim Answer As String
Dim Code As String = "m[n-Msr0Xn*ca8qiGeIL""7'&;,_*EV{M;[{2bEmg8u!^s*+O37!692{-Y4IS"
x = CType(Microsoft.VisualBasic.VBMath.Rnd(-7), Integer)
For r = 0 To sList.Length - 1
x = CType(Microsoft.VisualBasic.VBMath.Rnd() * 96 - 0.5, Integer)
c = Asc(sList.Substring(r, 1))
c = c + x
If c >= 126 Then c = c - 126 + 32
Answer &= Chr(c)
Next
Return Answer
End Function
but this is what I get "Bet you needed morB th(n a pencil and paper to get this one!"
I suspect its how I am castng to an int but I can't figure out how.
When I run your "Old Code" (after correcting the typos) under Office VBA (which should have the same Rnd implementation as VB6), I get the same result as you say you get from VB.Net. Therefore, there must be an error in the string assigned to Code.
Public Function Decode() As String
Dim r As Integer
Dim x As Integer
Dim c As Integer
Dim Code As String
Code = "m[n-Msr0Xn*ca8qiGeIL""7'&;,_*EV{M;[{2bEmg8u!^s*+O37!692{-Y4IS"
x = Int(Rnd(-7))
For r = 1 To Len(Code)
x = Int(Rnd() * 96)
c = Asc(Mid(Code, r, 1))
c = c + x
If c >= 126 Then c = c - 126 + 32
Decode = Decode & Chr$(c)
Next
End Function
Thanks to TnTinMan for leading me to the solution. The problem was created when I copied the string. I used a I instead of an l. The font that was used has these two characters looking identical. I also mistook ' for `.
so basically all I had to do was subtract .5

Getting error 438 in VBA Script

I have the following code. I debugged and got that the problem is with the IF inside the for.
The exact error is: Run Time Error 438 - Object Doesn't Support this Property or Method
Any clues what it could be?
I appreciate any help.
Thanks!
Sub dimensiones()
Dim Hoja1 As Object
Dim Hoja2 As Object
Set Hoja1 = Worksheets("INPUT")
Set Hoja2 = Worksheets("OUTPUT")
Dim inicio_filas As Integer
Dim col_s1 As Integer
Dim col_s2 As Integer
Dim limite_filas As Integer
Dim m As Integer
col_s1 = 38
col_s2 = col_s1 + 2
inicio_filas = 3
limite_filas = 1000
Dim k As Integer
k = inicio_filas
For i = inicio_filas To limite_filas
For m = 1 To col_s2 - 1
Hoja2.Cells(k, m) = Hoja1.Cells(i, m)
Next m
k = k + 1
If Hoja1(i, col_s2) <> "" Then
For m = 1 To col_s1 - 1
Hoja2.Cells(k, m) = Hoja1.Cells(i, m)
Next m
Hoja2.Cells(k, col_s2) = Hoja1.Cells(i, col_s2)
Hoja2.Cells(k, col_s2 + 1) = Hoja1.Cells(i, col_s2 + 1)
Hoja2.Cells(k, col_s2 + 2) = Hoja1.Cells(i, col_s2 + 2)
k = k + 1
End If
Next i
End Sub
Got it, noob error but forgot the Cells command missing when looking for Hoja1.Cells(i,col_s2)
Thanks!

Run function for multiple data sets and output results to different cells

I have been trying forever to try and figure this out. I have a set of data in a certain sheet in my Excel file. I have written code so that it outputs some of that information to another sheet. I don't know how to get the function to loop through all the different data sets and output them into the "Output" sheet in my excel file on different rows.
This is what I have so far. Can someone please help?
How do I get the function to run through about 6 data sets that include 5 cells in the column until there are 2 blank cells?
How do I output those different results to another sheet? I already have them outputting the first data set and it works fine. I just need to know how to do the other ones.
Thank you!
Sub EstBatch()
'variables
Dim N As String
Dim D As Date
Dim P As Integer
Dim H As Single
Dim NS As Integer
Dim NL As Integer
Dim BP As Currency
Dim OH As Single
Dim OC As Currency
Dim TP As Currency
Dim PPBR As Currency
Dim EHP As Single
Dim batches As Range
'inputs
N = Sheets("Batch Input").Range("A1").Value
D = Sheets("Batch Input").Range("B1").Value
P = Sheets("Batch Input").Range("A2").Value
H = Sheets("Batch Input").Range("A3").Value
PPBR = Sheets("User Form").Range("C22").Value
EHP = Sheets("User Form").Range("C23").Value
Range("A1").Select
'Processes
BP = P * PPBR
OH = H - 5
If P > 120 Or P < 20 Then
MsgBox ("Cannot Accommodate Group")
ElseIf P >= 20 And P <= 25 Then
NS = 1
NL = 0
ElseIf P >= 26 And P <= 50 Then
NS = 2
NL = 0
ElseIf P >= 51 And P <= 60 Then
NS = 0
NL = 1
ElseIf P >= 61 And P <= 85 Then
NS = 1
NL = 1
ElseIf P >= 86 And P <= 120 Then
NS = 0
NL = 2
End If
If OH > 4 Then
OH = 4
OC = BP * OH * EHP
ElseIf 0 < OH <= 4 Then
OC = BP * OH * EHP
ElseIf OH <= 0 Then
OC = 0
End If
TP = BP + OC
'outputs
Sheets("Batch Output").Range("A2").Value = N
Sheets("Batch Output").Range("B2").Value = D
Sheets("Batch Output").Range("C2").Value = P
Sheets("Batch Output").Range("D2").Value = H
Sheets("Batch Output").Range("E2").Value = PPBR
Sheets("Batch Output").Range("F2").Value = EHP
Sheets("Batch Output").Range("G2").Value = NS
Sheets("Batch Output").Range("H2").Value = NL
Sheets("Batch Output").Range("I2").Value = BP
Sheets("Batch Output").Range("J2").Value = OH
Sheets("Batch Output").Range("K2").Value = OC
Sheets("Batch Output").Range("L2").Value = TP
End Sub
Welcome to StackOverflow. Great first question.
I think what you're reaching for is how to use loops in solving a problem like this.
One easy way to do loops is with a counter, as in the examples I've given below. If appropriate, you can also use a range of cells to loop through data, as described in this answer: https://stackoverflow.com/a/19394207/2665195.
Starting with your second question: if you want a separate sheet for each output you can use Sheets.Add and paste into that new sheet. To do this you will want to use a variable naming convention like Sheets("Batch Output" & X).Range. In this way you can Dim X as Integer and loop through the process incrementing the X integer with each loop. Here's some sample code you can adapt for your purpose:
Sub ExampleAddSheets()
Dim intX As Integer
intX = 1
Dim wsBatchOutput As Worksheet
For intX = 1 To 6
Set wsBatchOutput = Worksheets.Add 'adds a worksheet and tags it to a variable
wsBatchOutput.Name = "BatchOutput" & intX 'names the worksheet
wsBatchOutput.Range("A1").Value = "Data here. Example " & intX
Next intX
Set wsBatchOutput = Nothing
End Sub
I don't know what your data source looks like, but hopefully it is set up in a way that you can turn the inputs aquisition into a loop. For example, if the data came into the system in rows (which your example does not seem to do) you could just increment the row number, something like this:
Sub ExampleSetInputs()
'variables
Dim N As String
Dim D As Date
Dim P As Integer
Dim H As Single
Dim PPBR As Currency
Dim EHP As Single
Dim intRow As Integer
intRow = 2
'inputs
For intRow = 2 To 7
N = Sheets("Batch Input").Range("A" & intRow).Value
D = Sheets("Batch Input").Range("B" & intRow).Value
P = Sheets("Batch Input").Range("C" & intRow).Value
H = Sheets("Batch Input").Range("D" & intRow).Value
Next intRow
End Sub
I hope this helps with your challenge.

addition of items in a listbox

Bellow pls find the code in VB 2008. I must sum up the numbers in the xlistscorebox
Dim tot As Integer
Dim scoresentered As Integer
For index As Integer = 0 To Me.xListscoreBox.SelectedItems.Count - 1
tot = tot + Val(Me.xListscoreBox.SelectedItems.Count)
For se As Integer = 0 To Me.xListscoreBox.SelectedItems.Count - 1
scoresentered = Me.xListscoreBox.SelectedItems.Count
Next
Next
Me.xscoreave.Text = tot / scoresentered.ToString
Me.xtotalscoreTextBox.Text = tot.ToString
Me.xtotscoreentered.Text = scoresentered.ToString
The issue is that the calculation is giving wrong results.
Any comment will be highly appreciate.
Cecilia
Dim TotalScore as Integer
For Each x As String In Me.xListscoreBox.SelectedItems
TotalScore = TotalScore + Convert.ToInt32(x)
Next
dim AverageScore as Decimal = TotalScore / Me.xListscoreBox.SelectedItems.Count
dim ScoresEntered = Me.xListscoreBox.SelectedItems.Count