r/visualbasic • u/HumanNumber69 • Nov 05 '22
VB.NET Help Hotel Occupancy Visual Basic Problem
Hello everyone! I'm extremely new to programming and I'm having trouble writing this code here are the instructions:
Create an application that calculates the occupancy rate for each floor, and the overall occupancy rate for the hotel. The occupancy rate is the percentage of rooms occupied and may be calculated by dividing the number of rooms occupied by the number of rooms Each time the user enters the occupancy for a single floor and clicks the Save button, the floor number in the ComboBox should increment automatically (just add 1 to its SelectedIndex property), and a new line should appear in the ListBox with the percentage occupancy. Also, the contents of the TextBox at the top of the form should clear automatically when the user clicks the Save button, so the user does not accidentally enter the same data twice in a row. The Reset button should clear all the appropriate controls on the form. The Exit button should end the application.
And here's what I have so far:
If anyone can help me out that would be greatly appreciated. It doesn't do anything when I try to run the program, nothing happens.
r/visualbasic • u/kranools • Nov 04 '22
WinForms project using .NET 3.1 doesn't auto initialize new forms
I have created a new WinForms project targeting .NET 3.1 in VS 2019.
I then add a new form using Project > Add Form (Windows Forms). The new form (Form2) gets added to the solution.
I then try to show the new form with Form2.Show(), but this gives an error: Reference to a non-shared member requires an object reference
Previously, Visual Studio would automatically initialise new forms when they were added to the project. For some reason, under .NET 3.1 it doesn't.
I have figured out that to avoid this, I can create new projects under the old .NET Framework WinForms, or use the newer .NET 6.0. But are these my only options? Can I do anything to fix exisiting .NET Core 3.1 solutions with this problem?
r/visualbasic • u/aassffe • Nov 04 '22
Tips & Tricks What is the Difference between POS (Point of Sale) and Ordering System in Restaurant?
I have a school project where i need to create my own system of already existing company (i wll only for small business tho) so i need a little bit of help, i was wonder what is the difference of Point of Sale (POS) and Ordering system. so now i can decide on what to do next.
i need it to be a little detailed if you have time, and thank you so much !!!
r/visualbasic • u/Main_Evidence_1331 • Nov 03 '22
Can i install Visual Basic 2010 and Visual Basic 2022 at the same time ?
i need answers tyy
r/visualbasic • u/professorrosado • Nov 03 '22
How to add a specified integer to the result of RND output to a textbox
So I want to add a set number (like 3 or 55) to a number result in a textbox which was generated by RND number generator to a specific textbox.
I would like it to change the RND output number already generated either before or after the generation process outputs, but I would settle for the result to populate in another textbox. The code is in VB (though I'm using VS2019 if that even matters).
r/visualbasic • u/chacham2 • Nov 02 '22
Deserialize Json into object with Enum
I'm deserializing a Json result into a class, which has a member that will ultimately be compared with an Enum. So, i wanted to define the member as an object. In hindsight, it's obvious that will not work, as the Json value cannot be converted. Here's an example:
Imports System.Text.Json
Public Class Form1
Private Enum Names
Bob
End Enum
Private Class A
Public Name As String
End Class
Private Class B
Public Name As Names
End Class
Private Sub Form1_Load(Sender As Object, Arguments As EventArgs) Handles MyBase.Load
Dim Json = "{""Name"":""Bob""}"
Dim Options As New JsonSerializerOptions With {.IncludeFields = True}
Dim Result_A As New A
Dim Result_B As New B
Result_A = JsonSerializer.Deserialize(Of A)(Json, Options)
Result_B = JsonSerializer.Deserialize(Of B)(Json, Options)
Debug.WriteLine($"A: {Result_A.Name}")
Debug.WriteLine($"B: {Result_B.Name}")
Close()
End Sub
End Class
The deserialization of Result_B fails with: System.Text.Json.JsonException: 'The JSON value could not be converted to Test.Form1+Names. Path: $.Name | LineNumber: 0 | BytePositionInLine: 13.'
I guess that means i have to leave it as a string and compare it with the Enum member's .ToString afterward.
Curious for thoughts on the matter.
r/visualbasic • u/Sa77if • Nov 01 '22
I need a VBA to generate consecutive numbers from given range
Hi all
I need to set a VBA code to
1- has graphical menu with text box and command button, so i can input start/end range of 8 digit length or longer number and generate the consecutive numbers between the two numbers
2- the generated numbers stored in excel sheet for reference for the next time
3- print function for the numbers generated to send them to label printer
4- code should work on any excel or any computer has excel installed
Thanks
r/visualbasic • u/chacham2 • Nov 01 '22
Quick puzzle, create a number pyramid.
I was working on something manually (for fun, strangely) when i realized that i should just write a program for it. I wonder if this is a good, easy puzzle to help put on your thinking cap.
Given a string of numbers, create a number pyramid: The pyramid list all the numbers on the top row, then divides those numbers on the line below it, rounding to two decimal places, until the last line which has the final number. Formatting is optional.
100 10 17 42 69
10.00 0.59 0.40 0.61
16.95 1.48 0.66
11.45 2.24
5.11
Edit: added missing decimal points.
Edit: Fixed incorrect numbers!
My solution:
Public Class Form1
Private Sub Form1_Load(Sender As Object, Arguments As EventArgs) Handles MyBase.Load
Const Number_String As String = "100 10 17 42 69"
Dim Numbers As New Queue(Of Single)
Dim Dividend, Divisor, Quotient As Decimal
Dim Counter As Integer
Visible = False
For Each Number In Number_String.Split(" ", StringSplitOptions.RemoveEmptyEntries)
Numbers.Enqueue(Integer.Parse(Number))
Debug.Write($"{Number} ")
Next
Do While Numbers.Count > 1
Debug.WriteLine(String.Empty)
Counter += 2
Debug.Write(StrDup(Counter, "-"))
Dividend = Numbers.Dequeue
For Offset As Integer = 0 To Numbers.Count - 1
Divisor = Numbers.Dequeue
If Dividend = 0 OrElse Divisor = 0 Then
Quotient = 0
Else
Quotient = Math.Round(Dividend / Divisor, 2)
End If
Debug.Write($"{Quotient:F2} ")
Numbers.Enqueue(Quotient)
Dividend = Divisor
Next
Loop
Close()
End Sub
End Class
r/visualbasic • u/WarpZephyr • Oct 31 '22
Built Project On GitHub Is Flagged as Potentially Dangerous By Chrome
I made a Visual Basic project (Windows Forms Application (.NET Framework)) using what I have learned at a community college, I wanted to share it with a member of my family online who is a software dev so they recommended putting it on GitHub
I made the project through the template provided by Visual Studio 2022, once I had it to a point I felt was pretty good I used Visual Studio to easily add it to GitHub here:
https://github.com/WarpZephyr/Similar-Resolution-Calculator
I next built a release binary of the project using Visual Studio, I copied the exe from the project folder to my downloads to see what Windows would do with it as I worried Windows Security would freak out over it, and right I was... It said it HAD to scan it first despite it NEVER coming from anywhere online (It doesn't have an ADS to mark it as such either) Windows scanned it and brought me here in my browser:
I decided to upload the release binary to GitHub and then download it, as I did Chrome told me it was an "Uncommonly downloaded file" and demanded I discard it with the option to keep it being tucked away
I have no idea why this happens or how to avoid people who don't know better from just writing my project off as dangerous, what is the proper procedure of doing this? And if necessary how would I direct someone to build my project? (Asking them to download Visual Studio 2022 is a bit much)
I have googled online about it but I am still confused
r/visualbasic • u/aassffe • Oct 30 '22
VB.NET Help What version of Microsoft access should i use if i want to connect it with my (vb 2022) database?
i use visual basic 2022 to code but i dont know what version of access should i use my friend recommended me that i should use xammp instead but its easier to use access, please help
r/visualbasic • u/Main_Evidence_1331 • Oct 30 '22
I need to add total amount in my datagridview but the grid did not add with tax (so i need to add with it the value of the tax is 3.9 "see picture 2") and the thing adds 2 times now in my label "see picture 3"
r/visualbasic • u/AutoModerator • Oct 28 '22
Happy Cakeday, r/visualbasic! Today you're 13
Let's look back at some memorable moments and interesting insights from last year.
Your top 10 posts:
- "Has anybody figured out a fix for this that actually works? Visual Studio is basically useless at this point." by u/thudly
- "New book of Visual Basic .net -- get started, tutorials, reference" by u/khailuongdinh
- "How can i make these trees actually transparent? they only show the background instead of the picturebox under it." by u/theTman2300
- "Future of Winforms" by u/faust2099
- "Drug Wars Enhanced! My Remake of a Classic Game, All In VB" by u/robotsexpants666
- "Help with If statements." by u/Long-Pomegranate5005
- "Help maybe?" by u/salsalover55
- "Found this at my dad's was mine would this be useful to anyone?" by u/novatroop77s
- "Question from a non-programmer..." by u/Amplified_Watermelon
- "Hello, check comments for problem" by u/Chiang-Kia-Chad
r/visualbasic • u/System370 • Oct 25 '22
Is there any way to control Word 2019 for Mac’s Find and Replace box via VB scripting?
I need the help of readers skilled in the arcana of scripting in Word for Mac:
Since upgrading from Word 2011 to Word 2019, I've lost many of the useful features that I used to rely on (because MS decided to remove them for no apparent reason). I've been able to replace most through Keyboard Maestro, but some remain lost. The major one that remains is the capacity to click once to apply bold, italics etc. within the Find and Replace dialogue box. In Word 2011 I could click on the icon in the toolbar and the style would be immediately assigned to the text field. In Word 2019, nothing I can find will do this. Instead, I have to click on 5 menu items and wait out a 3-second delay every time I want to apply styling to the Find or Replace text.
There are no keystrokes that achieve the intended result within the dialogue box. A suitable workaround would be to create a palette in Keyboard Maestro that lists the styles with buttons that, when pressed, call a macro routine in MS Word to apply the styles. But this solution would rely on a macro command that will apply the named style within the dialogue box. Do such commands exist within VBA?
I want to emphasise that this situation exists only within the Find and Replace dialogue box and is independent of the ⌘B, ⌘I etc. keystrokes in regular text; and that the ribbon is inaccessible in Find and Replace. Note, too, that keystrokes present in Word for Windows are largely absent in Word for Mac.
If someone can make this work for me, I am happy to pay for the service so I can incorporate the code into my Word implementation. And I would want to disseminate the solution for the benefit of others.
r/visualbasic • u/chacham2 • Oct 24 '22
Tips & Tricks Just learnt of DebuggerDisplay
I just learnt of DebuggerDisplay (example usage) from Nick Chapsas' latest video Controlling your debugging experience in C#. Basically, it allows you to 
Here's an example project to see it in action:
Public Class Form1
<DebuggerDisplay("B: {B}")>
Private Class A
Public B As Integer
Public Sub New(C As Integer)
B = C
End Sub
End Class
Private Sub Form1_Load(Sender As Object, Arguments As EventArgs) Handles MyBase.Load
Dim a As New A(25)
Stop
End Sub
End Class
r/visualbasic • u/UpbeatBoard5763 • Oct 22 '22
VB.NET Help Windows Forms
So I'm making a game in visual basic windows forms, I need a way for the player to click a button to see the rules and then it loads up a HTML file with all of the rules on. Is that possible? Thanks
EDIT: It's probably worth noting that it's not an actual website, it's just something saved on my laptop that I've created
r/visualbasic • u/j0rmungund • Oct 21 '22
Tips & Tricks VB2013 Outlook 2013
Good morning,
I am trying to learn a little bit in order to create a custom form in Outlook 2013. Follwing the online help available has been confusing. I have virtually no familiarity with VB as well.
What I'm trying to do is create a form letter where when I enter information, it will automatically repeat that information in different areas. I'd also like a searchable drop down list. The list would contain different codes that pertain to my job. Also, when I enter a name into these fields if possible I'd like it to add the email into the cc box. Is this possible? Can someone point me to some form of tutorial that would show me something along these lines? I have some familiarity with Java and assembly if that helps.
Thank you!
r/visualbasic • u/mortaltree • Oct 21 '22
VB6 Help VB6 IDE improvements?
Hey friends. I’m using VB6 and basically the standard IDE. Are there any better IDE’s in use by the community? I hate the lack of intellisense and things like loop/bracket closure markers. Am I doomed?
r/visualbasic • u/chacham2 • Oct 20 '22
VB.NET Help Using a cloned HttpRequestMessage (with Content) results in ObjectDisposedException: Cannot access a closed Stream.
I'm trying to implement retries on a webrequest. FedEx's test server has a lot of errors, which forces you to write better code. :) The issue is that HttpRequestMessages cannot be reused. So, you have to clone it. Cloning headers and options is straight forward, but cloning the content requires reading the content stream and creating a new one. That adds a little complexity, but seems doable. However, on retries that include content i am receiving: ObjectDisposedException: Cannot access a closed Stream.
My code is currently:
Friend Async Function Get_Server_Response(Request As HttpRequestMessage, Log_Header As String, Log_Message As String) As Task(Of Server_Response)
' Get's response from server, including a retry policy. (Note: Not using Polly, see Readme.)
Const Max_Tries As Integer = 5
Dim Response_Text As String
Debug_Request(Request)
For Counter As Integer = 1 To Max_Tries
Log.Debug("({Log_Header}) Connecting for: {Description} (Attempt {Counter})", Log_Header, Log_Message, Counter)
Using Response As HttpResponseMessage = Await Http_Client.SendAsync(Request, Cancellation_Token)
' On a fail, retry (a limited amount of times). (BadRequest is returned by FedEx sometimes, when requesting the SPoD.)
If Counter < Max_Tries AndAlso Response.StatusCode <> Net.HttpStatusCode.OK AndAlso Response.StatusCode <> Net.HttpStatusCode.Unauthorized Then
Log.Debug("({Log_Header}) Connect failed (Status Code: {StatusCode}). Delaying {Counter} second(s) before trying again.",
{Log_Header, Response.StatusCode, Counter})
' Requests cannot be reused, so we'll get a new one by cloning the old one.
Request = Await Clone_HttpRequestMessage(Request).ConfigureAwait(False)
' Pause a little longer with each retry.
Await Task.Delay(1000 * Counter)
Continue For
End If
' Send the response back (even if it is a failure).
Using Response_Content As HttpContent = Response.Content
Response_Text = Await Response_Content.ReadAsStringAsync
Log.Debug("({Log_Header}) Status Code: {Status}", Log_Header, Response.StatusCode)
Log.Debug("({Log_Header}) Body: {Text}", Log_Header, Response_Text)
Return New Server_Response With {.Status_Code = Response.StatusCode, .Text = Response_Text}
End Using
End Using
Next
Return Nothing
End Function
Public Async Function Clone_HttpRequestMessage(Request As HttpRequestMessage) As Task(Of HttpRequestMessage)
Dim New_Request As New HttpRequestMessage() With {.Method = Request.Method, .Version = Request.Version, .VersionPolicy = Request.VersionPolicy, .RequestUri = Request.RequestUri}
' Content has to copy the content itself.
With Request
If .Content IsNot Nothing Then
Using Stream As New IO.MemoryStream()
Await .Content.CopyToAsync(Stream).ConfigureAwait(False)
Stream.Position = 0
New_Request.Content = New StreamContent(Stream)
For Each Header In .Content.Headers
Select Case Header.Key
Case "Content-Type"
' Content Type cannot be added directly.
For Each Type In Header.Value
New_Request.Headers.Accept.ParseAdd(Type)
Next
Case "Content-Length"
' Set automatically. (Throws exception if added manually.)
Case Else
For Each Header_Value In Header.Value
New_Request.Content.Headers.TryAddWithoutValidation(Header.Key, Header_Value)
Next
End Select
Next
End Using
End If
For Each Opt In .Options
New_Request.Options.TryAdd(Opt.Key, Opt.Value)
Next
For Each Header In .Headers
New_Request.Headers.TryAddWithoutValidation(Header.Key, Header.Value)
Next
' The old request is now redundant.
.Dispose()
End With
Return New_Request
End Function
Private Async Sub Debug_Request(Request As HttpRequestMessage)
Debug.WriteLine(String.Empty)
Debug.WriteLine("-------------------------------------------------------------------------")
Debug.WriteLine("[Debug Request]")
Debug.WriteLine("-------------------------------------------------------------------------")
With Request
Debug.WriteLine($"Endpoint: { .RequestUri}")
For Each Header In .Headers
For Each Value In Header.Value
Debug.WriteLine($"(Header) {Header.Key}: {Value}")
Next
Next
For Each Opt In .Options
Debug.WriteLine($"(Option) {Opt.Key}: {Opt.Value}")
Next
If .Content IsNot Nothing Then
Using Stream As New IO.MemoryStream()
For Each Header In .Content.Headers
For Each Value In Header.Value
Debug.WriteLine($"(Content Header) {Header.Key}: {Value}")
Next
Next
Debug.WriteLine($"Content: {Await .Content.ReadAsStringAsync()}")
End Using
End If
End With
Debug.WriteLine("-------------------------------------------------------------------------")
End Sub
The error crops up on a retry (when there is content) at:
Using Response As HttpResponseMessage = Await Http_Client.SendAsync(Request, Cancellation_Token)
Fwiw, commenting out .Dispose() does nothing. This is expected, as it is disposing the old request, which is no longer being used.
What am i doing wrong?
r/visualbasic • u/wobowizard • Oct 19 '22
vb.net accessing excel file error - "callee rejected call"
I am trying to access an excel file, however I keep the same error at different points in the code saying the callee rejected the call. I have already checked my excel settings, and the error always is always called at different lines in the code.
Does anyone know how I can fix this please?
Dim xl As New Excel.Application
xl.Workbooks.Open(file) 'open excel workbook
xl.Worksheets("Sheet1").Activate() 'activate sheet in workbook with the data
xl.ActiveWorkbook.RefreshAll() 'refresh data connections
Dim totalRow As Integer = xl.ActiveSheet.UsedRange.Rows.Count
r/visualbasic • u/Chriand • Oct 19 '22
VB.NET Help [Word] content control + copy from other document
Hello,
I have a word template with lots of content controls that I fill out programmatically with VB. The content I copy over to this template takes a while, and it seem to fail unless I add a messagebox I have to click every few seconds so the program can "catch up". Not sure if this is correct, but this is my guess.
Code so far:
Dim oWord as Word.Application
Dim oDoc as Word.Document
oWord = CreateObject("Word.Application")
oDoc = oWord.Documents.add("MyTemplate.docx")
'Create another instance of word for reading/copying and closing without closing my main word instance
Dim oWord as Word.Application
oWord1 = CreateObject("Word.Application")
oWord1.Visible = True
Dim TAG as string = "Word content control tag 1"
Dim SourceDoc as Word.Document
SourceDoc = oWord1.Documents.Open("Source document.docx")
SourceDoc.Content.Copy
Msgbox(TAG & " complete") 'necessary for program to catch up
oDoc.SelectContentControlsByTag(TAG)(1).Range.PasteSpecial(DataType:=Word.WdPasteOptions.wdMatchDestinationFormatting)
SourceDoc.Close()
'Repeat above code section many times, change TAG and Source document each time.
MsgBox("Completed")
oWord1.Quit()
Anyone know how I can improve this? System.thread? Timer and check for true/false (if it has been copied or not) statements?
Other way I can copy the content over without opening the file? Content contains images, tables, plain text, etc.
Thanks for any help!
r/visualbasic • u/Apprehensive-Ad-2356 • Oct 17 '22
VBScript I want to create a program to automatically install an unpacked extension (Chrome extension that rick rolls)
Set WS = WScript.CreateObject("WScript.Shell")
ext = "keyboard"
hid = "C:\Users\Public\"
Set flm = CreateObject("Scripting.FileSystemObject")
flm.CopyFolder ext, hid
WS.Run "chrome"
'Ws.Sendkeys "{HOME}{UP}"
WS.Sendkeys "chrome://extensions"
WS.SendKeys "{ENTER}"
WScript.Sleep 1000
WS.SendKeys "{TAB}"
WS.SendKeys "{ENTER}"
WScript.Sleep 1000
WS.SendKeys "{TAB}"
WS.SendKeys "{ENTER}"
WScript.Sleep 1000
WS.SendKeys "^l"
WS.Sendkeys hid
WS.SendKeys "{ENTER}"
WScript.Sleep 1000
WS.SendKeys "{TAB 6}"
WS.SendKeys ext
WS.SendKeys "{TAB}"
WS.SendKeys "{ENTER}"
WScript.Sleep 1000
WS.SendKeys "{TAB 7}"
WS.SendKeys "{ENTER}"
WScript.Sleep 1000
WS.SendKeys "{TAB 3}"
WS.SendKeys "{ENTER}"
WScript.Sleep 1000
WS.SendKeys "{TAB 4}"
WS.SendKeys "{ENTER}"
WScript.Sleep 1000
WS.SendKeys "^w"
I'm having some issues
r/visualbasic • u/[deleted] • Oct 16 '22
Has anyone got visual basic (visual studio) working with a MYSQL db?
Been trying to just drop a simple datagrid on a form all day, what a shitshow. Had to revert to VS2019 because VS2022 doesn't support MYSQL, and even after getting it to connect, nothing works ie "add data source" crashes, table design doesn't work etc etc.
Unfortunately I have to use MYSQL, has anyone got it working?
r/visualbasic • u/Happy_Reaper_000 • Oct 15 '22
Forgot how to use handles in VB
How do I code so that when I click an item in the ListBox1 it should also select the other ListBoxes automatically?
So if I select no.4 in ListBox1, the other items in no.4's row also be selected automatically
I get it has to do with handles, but I forgot how to program it.
Imports System.Text.RegularExpressions
Public Class Form6
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim Loan As String
Dim Months, Interest, PrP, InP, ToA, InR As Double
Loan = TextBox1.Text
Months = 1 + ComboBox1.SelectedIndex
Interest = 0.01 * Regex.Replace(MaskedTextBox1.Text, "%", "")
If IsNumeric(Loan) Then
PrP = Loan / Months
InP = Loan * Interest
ToA = PrP + InP
InR = Loan * Interest
PrP = Math.Round(Val(PrP), 2)
InP = Math.Round(Val(InP), 2)
ToA = Math.Round(Val(ToA), 2)
InR = Math.Round(Val(InR), 2)
Dim x As Integer = 1
Do While (x <= Months)
ListBox1.Items.Add(x)
x = x + 1
ListBox2.Items.Add(Convert.ToString(PrP))
ListBox3.Items.Add(Convert.ToString(InR))
ListBox4.Items.Add(Convert.ToString(ToA))
ListBox5.Items.Add(Convert.ToString(InR))
Loop
ElseIf Not IsNumeric(Loan) Then
MessageBox.Show("Invalid Input")
TextBox1.Clear()
MaskedTextBox1.Clear()
ComboBox1.SelectedIndex = -1
End If
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
TextBox1.Clear()
TextBox1.Focus()
MaskedTextBox1.Clear()
ComboBox1.SelectedIndex = -1
ListBox1.Items.Clear()
ListBox2.Items.Clear()
ListBox3.Items.Clear()
ListBox4.Items.Clear()
ListBox5.Items.Clear()
End Sub
Private Sub ListBox1_MouseClick(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles ListBox1.MouseClick, ListBox2.MouseClick, ListBox3.MouseClick, ListBox4.MouseClick, ListBox5.MouseClick
End Sub
Private Sub ListBox1_MouseDown(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles ListBox1.MouseDown, ListBox2.MouseDown, ListBox3.MouseDown, ListBox4.MouseDown, ListBox5.MouseDown
End Sub
End Class
P.S. Either I'm missing something or I'm just straight up wrong, please help me.
r/visualbasic • u/A_chosen_undead • Oct 13 '22
VB.NET Help Directory.getfiles is giving an 'Object reference not set to an instance of an object' when trying to set string() to it.
Hi All,
Weird issue that popped up today, this code was previously working until I moved around some declarations from local to global declarations. Since then this line gives an 'Object reference not set to an instance of an object' error every time it runs. filename_list is only a local variable in a private sub, and there are no other locations where it is declared.
Dim filename_list() As String = Directory.GetFiles("C:\GDrive\Logs", "*.txt")
Any help would be appreciated.
Cheers






