/r/visualbasic

Photograph via snooOG

A place to discuss, ask questions and share ideas regarding the Visual Basic programming languages.

/r/VisualBasic - A place to discuss, ask questions and share ideas regarding the Visual Basic programming languages.

Please up vote anybody who helps with your submission, we want people to keep answering questions.

Tips & Guidelines

  • Please prefix your posts with the version of Visual Basic you are using. Example: [VB2010] - [VB2015], [VB6], [VBSCRIPT], [VBA]
  • Posting any code you have will help others better understand what you are trying to do and what you have tried already, even if it doesn't work properly. It also shows that you already tried to solve your problem.
  • If you ask for help, you should come back and let us know how things turned out.
  • Homework questions are tolerated, please be specific about the question as much a possible. Asking us to write it for you is not going to happen. We also reserve the right to not answer if we think you are just not trying.
  • Tell us what you have tried, to help us give better answers?

Communities

Resources

Learning Visual Basic

Related Subreddits

/r/visualbasic

9,155 Subscribers

1

Anyone here do small gigs?

I need a bit of code to customize a spreadsheet to send certain emails to individuals listed within. Do any of you experts take on small jobs or can you send me to a good source? I didn’t feel as comfortable with fiverr or similar.

5 Comments
2024/12/19
11:40 UTC

1

advice needed...

Hi everybody!
I'm studying to be able to land, one day, a programming job, but I'm also getting ready for the summer, where I live jobs revolve around tourism and I'll try to get a part time job in an hotel like every year. Excel is a nice skill to have, but unfortunately I don't have many chances to use it in my day-to-day life. VBA is seen as an "expert" thing here and so even nicer to add to the resume, and even if I kinda like the language (played a bit with VB6 as a teenager) and it "clicks" with me (more so than C despite having used it for much longer), I'm afraid I'll forget it if I don't use it during the winter (I study system programming in winter months, my true passion!). I know a lot of people frown upon vb.net as a language for .net learners and tend to suggest c#, but I opened up VS community, tried a VB console app and wow, the syntax seems sooo similar... and it's a lot more likely I'll use .net for some interesting project than excel/vba... and here is the question... would it be ok for me to study vb.net after learning vba, in order to both learn something about .net and, even more important, not forget vba before the next year? Ty all!!

6 Comments
2024/12/17
18:43 UTC

4

I messed up. Rookie mistake

So after many hours trying to make this userform, all learning as I go and lots of chatGPT/Co-pilot/Claude "Messing up" I realized I am the one who has been messing up. I've been coding excluseivly in the userform, none in the actual document. Now totally unsure what can stay and what should go into the document. As of now (before moving anything) everything works so far except what I've spent the most time trying to accomplish.
Send help If anyone would care to help me figure out how to move the correct stuff and maintain the function, I would greatly appreciate it... https://pastebin.com/0ggiHX3L

0 Comments
2024/12/17
06:10 UTC

2

Eval in VB.NET? (Forms)

Hi! I was making a small "CLI"-like project and need help to make the eval command, in this case it would be an evaluate command:

Here's my code (the eval function don't work):

Imports System.Windows.Forms

Public Class Form1

    Dim computerName As String = Environment.MachineName

    Public Function SimpleEval(expression As String) As Object
        Dim result As Object
        Try
            ' Allow simple arithmetic operations and variable assignments
            result = DirectCast(Evaluate(expression), Object)
        Catch ex As Exception
            result = "Error: " & ex.Message
        End Try
        Return result
    End Function

    Private Sub TextBox1_KeyDown(sender As Object, e As KeyEventArgs) Handles TextBox1.KeyDown
        If e.KeyCode = Keys.Enter Then
            Dim userInput As String = TextBox1.Text

            SimpleEval(userInput)
            Label1.Text = "> [" & computerName & "]:" & userInput
            'TextBox1.Text = ""  ' Clear the textbox
        End If
    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        TextBox1.Focus()
    End Sub
End Class
2 Comments
2024/12/16
19:46 UTC

3

Insert new paragraph in body

I've been back and forth with Co-Pilot and ChatGPT, but both kept suggesting this InsertParagraphAfter line. I'm not sure how to make it work since it seems like that's the most suggested either way. Anyways below is what I ahve. I want to add a line below a content control if possible on a button press. I want to make it a function so that I can use it elsewhere as there are multiple lines I want to add occasionally.

I'm extremely new to coding in general, and I know there are probably a lot of ways to accomplish this templare and software project. Would love any help

Edit, because I forgot the important part. Currently getting error 424 due to the line

If wordApp Is Nothing Then.

This project is being done in Word. And I'm using word 2016

Current iteration:

Private Sub btnAdditionalWork_Click()

Dim wordApp As Word.Application

Dim doc As Word.Document

' Get Word application

Set wordApp = Application

' Get active document

Set doc = wordApp.ActiveDocument

' Add a new paragraph at the end of the document

doc.Paragraphs.Add(doc.Range.End).Range.text = "New list item"

' If the previous paragraph was a list item, apply the same list format

If doc.Paragraphs(doc.Paragraphs.count - 1).Range.ListFormat.ListType <> wdListNoNumbering Then

doc.Paragraphs(doc.Paragraphs.count).Range.ListFormat.ApplyListTemplate _

listTemplate:=doc.Paragraphs(doc.Paragraphs.count - 1).Range.ListFormat.listTemplate

End If

End Sub

Current error: Type mismatch

doc.Paragraphs.Add(doc.Range.End).Range.text = "New list item"

14 Comments
2024/12/16
02:24 UTC

3

Playing two audio clips at the same time?

So I have been working on a school project and I am having trouble figuring out how to play two different sounds at the same time, since the project I am working on is meant to be a game and it'd be very weird for a game to not have sound. Obviously I know that Visual Basic isn't meant for games but I figured there'd still be a way to play two or more sounds at once.

6 Comments
2024/12/14
04:30 UTC

2

Form change button not finding certain forms

Hi, I'm creating an HMI on VS 2019 and trying to use a form change button to get to different pages within the HMI. When I go to choose which form to open with said button some of the forms don't show up in the drop down of options. Any ideas why?

1 Comment
2024/12/13
15:58 UTC

3

Future-Proofing Business-Critical VB6 Applications: Need Guidance

Hello everyone,

My predecessor developed numerous programs in Visual Basic Classic 6.0, including business-critical applications and interfaces. Now that he has left the company, we are faced with the challenge of how to proceed with these applications. Microsoft officially ended support for VB6 in 2008, and we are concerned that the programs might stop working with future updates.

An upgrade from Windows 10 to 11 or even 12 has been planned for some time, and tests with Windows 11 are already underway at our parent company. Therefore, the question arises whether there is an estimate of how long the programs will continue to run smoothly, including database connections. How urgently should we look into external reprogramming?

Thank you in advance for your support and advice!

10 Comments
2024/12/09
10:52 UTC

3

Array help

I’m supposed to make an array for a soccer team and their scores that auto arranges from the teams with the most wins to least.

Then have a button that shows the scores (I know the button tool but the coding of the function is fuzzy).

However I have zero idea how to make the array, I’ve looked on Google and it’s all gibberish or I’m told to use a tool that I don’t have (for context I’m using 2022 version) let alone the coding associated.

Any help would be appreciated.

8 Comments
2024/12/05
02:07 UTC

3

You guys seem like experts, Can you help?

While working on a project I've come across a need for a large number of storage to be taken up by meaningless files, so i created a little vb.net project to do that. However I've come to a bottleneck and it's not as efficient as I need it to be (Currently 1GB in 20s), do you guys have any idea on how to improve it. Visual basic express 2010.

https://preview.redd.it/qn74hmetvs4e1.png?width=1087&format=png&auto=webp&s=5f7d55079d6224d2906b79dea54d46d26c37a836

1 Comment
2024/12/04
09:29 UTC

23

Using VB.NET gets you insulted by Microsoft

I was recently searching for something and found a great article on something related. While reading the comments I found some guy berating, insulting a belittling the article author for using VB.NET. While i currently use c#, i learned .NET using VB, and still like VB. And while I hate Java (from experience using it years ago), I can't imagine myself insulting someone who chooses to use Java. So I was pretty surprised and upset when I saw the comments from that guy, and even more upset when I learned he's a Senior at Microsoft for the past 8 years or so. As a fan of most Microsoft products and focused almost exclusively on the .NET framework and ecosystem, this hit me in a really sour spot. I personally feel developers are usually of a fact driven mindset, and are part of rather small communities in which many are contributors to. I feel these contributors should be thanked for giving without asking in return, and not bullied online. I just wanted to share my thoughts and what prompted my thoughts (see video below). And while my title may be a little misleading, employees of the major companies/players in our industry should be held to a slightly higher standard, in my opinion.

https://reddit.com/link/1h3ryg1/video/egxrtqnx454e1/player

17 Comments
2024/12/01
01:34 UTC

1

Please help im new to vb

How can i make vb run form 3 first instead of form 1 cant i just rename it or something

1 Comment
2024/11/28
05:36 UTC

21

My VB.NET 2D MMORPG Is Finally Complete!

Key To Heaven is my VB.Net passion project, a 2D MMORPG that I’ve been working on for almost 20 years. After years of dedication, I’m thrilled to announce that the game is finally complete and ready to launch!

Mark your calendars: on November 29th at 20:00 CET, the game will officially leave Early Access on Steam. Everyone will start fresh at level 1, embarking on this journey together. For me, this marks the beginning of some peace of mind, allowing me to shift my focus to smaller patches.

What’s it made in?

The game is built entirely in VB.NET.

  • The client runs on .NET 4.0 for compatibility with lower-end systems.
  • The server uses .NET 5.0. While I could upgrade to .NET 8, the current setup perfectly suits the project’s needs.

For graphics, I’ve relied on SFML, which has been a great fit for creating the retro aesthetic I envisioned.

Server Architecture

The server system is designed with flexibility in mind:

  • Each Realm can connect multiple servers, so, for example, I can host a server in both the US and EU, both syncing with the same database and master server.
  • This setup lets players seamlessly switch between servers to play with friends across regions, utilizing the same account & characters.
  • Players can even host their own Realms with custom servers and databases. These private Realms are independent of the official servers, so accounts created there won’t work on the main servers.

For custom Realms, players get all the tools they need to tweak game content—like adding new maps, items, monsters, and more. Plus, these custom servers will still show up in the game client’s server list for others to discover.

https://reddit.com/link/1h1betq/video/6444s8dhnh3e1/player

Why play it?

If you love retro-style indie games, Key To Heaven might be right up your alley. It has all the classic MMORPG staples: Randomized gear, crafting, raft, Questing, Raids...

But it also brings some fresh ideas to the table, like:

  • A built-in Battle Royale mode, where you can queue anytime for fast-paced, 2D combat with swords, bows, and spells. Ever tried that in a retro MMORPG?
  • Matchmaking for PvP, where you can safely face off against other players and climb the MMR leaderboard.

And there’s much more hidden beneath the surface, plenty to explore and discover as you play.

Website: https://key2heaven.com/

Download: https://store.steampowered.com/app/1347630/Key_To_Heaven/

Discord: https://discord.gg/TmHHJkG

9 Comments
2024/11/27
18:37 UTC

4

VB.NET api-wrapper for llm-inference chatllm.cpp

Hi. I used Llama 405b to make vb.net api wrapper for llm-inference chatllm.cpp: JohnClaw/chatllm.vb: VB.NET api wrapper for llm-inference chatllm.cpp

0 Comments
2024/11/26
16:56 UTC

2

Newbie trying to save data to a table...

Hello! I have an assignment for class where I need to be able to edit a table in a dataset that is open using the

Datagridview. When I execute the code I wrote nothing happens except the dialogue box pops up confirming a save has happened. Any ideas on how to actually get it to save? here's my code:

Private Sub SaveToolStripButton_Click(sender As Object, e As EventArgs) Handles SaveToolStripButton.Click

        Try
            Me.Validate()
            Me.MeatPartyBindingSource.EndEdit()
            Me.TableAdapterManager.UpdateAll(Me.MeatDataSet)
            MessageBox.Show("Changes saved successfully!", "Meat Info", MessageBoxButtons.OK, MessageBoxIcon.Information)
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Meat info", MessageBoxButtons.OK, MessageBoxIcon.Information)
        End Try

    End Sub

I learned this code from dissecting one of the exercises in the book. the book is Programming with Microsoft Visual Basics 2019/2022 by Dianne Zak

2 Comments
2024/11/23
09:16 UTC

2

Filtering a table based on multiple values in a column

I have in column h multiple names on a table called SYS

I need to keep only which values on column h does not contain David Sama Sught Maria

How can I achieve this ? Thanks

2 Comments
2024/11/22
18:38 UTC

3

VB script won't run after working once, baffled.

Hi all,

I have 0 experience with VB, but I cobbled this together today using google, stack overflow and chatgpt (I know, please don't hate me) and I managed to get it to work once, and it seemed to work perfectly it did exactly what I wanted, and then I tried to run it again, exact same code, just on a different excel workbook and it now does nothing when I run it. No errors asking me to debug or anything just runs fine but doesn't actually do anything.

Code is meant to take an excel sheet called "Transactions", and then randomly select 10% of the rows and copy them over to the 2nd sheet called "Random" basically got a list of transactions that relate to company spending and want to create a way to just get the transaction report, run the script, then I have 10% of the transactions randomly selected which I can use for spot checking.

Anyone got any ideas? Code below:

Sub RandomLinePicker()

'Define the Start and End of the data range

Const STARTROW As Long = 1

Dim LastRow As Long

LastRow = Sheet1.Cells(Worksheets("Transactions").Rows.Count, 1).End(xlUp).Row

'Create an Array - Length = Number of Rows in the data

Dim RowArr() As Long

ReDim RowArr(STARTROW To LastRow)

'Fill the Array - Each element is a row #

Dim i As Long

For i = LBound(RowArr) To UBound(RowArr)

RowArr(i) = i

Next i

'Shuffle the Row #'s within the Array

Randomize

Dim tmp As Long, RndNum As Long

For i = LBound(RowArr) To UBound(RowArr)

RndNum = WorksheetFunction.Floor((UBound(RowArr) - LBound(RowArr) + 1) * Rnd, 1) + LBound(RowArr)

tmp = RowArr(i)

RowArr(i) = RowArr(RndNum)

RowArr(RndNum) = tmp

Next i

'Calculate the number of rows to divvy up

Const LIMIT As Double = 0.1 '10%

Dim Size As Long

Size = WorksheetFunction.Ceiling((UBound(RowArr) - LBound(RowArr) + 1) * LIMIT, 1)

If Size > UBound(RowArr) Then Size = UBound(RowArr)

'Collect the chosen rows into a range

Dim TargetRows As Range

' Initialize TargetRows as Nothing

Set TargetRows = Nothing

' Assuming RowArr is already populated and Size is correctly calculated

For i = LBound(RowArr) To LBound(RowArr) + Size - 1

If TargetRows Is Nothing Then

Set TargetRows = Sheet1.Rows(RowArr(i))

Else

Set TargetRows = Union(TargetRows, Sheet1.Rows(RowArr(i)))

End If

Next i

'Define the Output Location

Dim OutPutRange As Range

Set OutPutRange = Worksheets("Random").Cells(1, 1) 'Top Left Corner

'Copy the randomly chosen rows to the output location

TargetRows.Copy Destination:=OutPutRange.Resize(TargetRows.Rows.Count).EntireRow

End Sub

Thanks all!

8 Comments
2024/11/22
13:11 UTC

3

Other VB6/VBA/VBScript gotchas?

I notices that, VB6/VBA/VBScript have a gotcha in its language design; where subsequent conditions of an if statement, are evaluated even though they're not supposed to.

For array e.g.:

arr = array(3, 4, 5)
i = ubound(arr) + 5 'beyond array length
if (i < ubound(arr)) and isempty(arr(i)) then
  rem above line causes exception
end if

In above code, arr(i) is not supposed to be evaluated. But it does anyway.

Same thing goes to collection. e.g.:

set fl = createObject("scripting.filesystemobject").getfolder(".").files
i = fl.count + 5 'beyond collection length
if (i < fl.count) and isempty(fl(i)) then
  rem above line causes exception
end if

Or object. e.g.:

set x = nothing
if (not (x is nothing)) and isempty(x.prop) then
  rem above line causes exception
end if

I already know the workaround for above gotcha, and I'm not asking for other workaround, or any alternative language.

I want to know any other kind of gotcha in VB6/VBA/VBScript.

19 Comments
2024/11/21
09:03 UTC

5

Proof of Concept: Breakout/Arkanoid Style Clone in MS Access VBA

Hi all - I created a MS Access VBA project that I haven't seen before; a Breakout (aka Arkanoid/Brick Breaker) style clone with the ball, paddle, and bricks. It still has a few bugs, glitches, and weird flickering, but I got it working!

Full code and file here: https://github.com/TLDWTutorials/BreakoutClone

I also made a YouTube video about it as well. See: https://www.youtube.com/watch?v=GLEZmrcn-Vc

Feel free to use it, optimize it, and make it your own.

0 Comments
2024/11/13
21:21 UTC

4

RWRUN60 CMD failure

Hi, My employer upgraded Oracle from 11g to 19c.Now the Oracle forms builder fails to connect to Oracle 19c.RWRUN60 CMD just vanishes once the creds are entered and nothing happens.

Anyone has any experience with this and any suggestions or fixes for this?

Forms builder 6i was earlier connecting to 11g and everything was working fine.

Please let me know if any additional info is needed from my end.

I have no knowledge or experience on VB.So seeking out for help

They thought it has to do with encryption in 19c and altered the sqlnet.ora file to setting LOGON.ENCRYPTION=rejected but dint help

1 Comment
2024/11/08
19:25 UTC

6

Vb to mobile

Hi guys! I've made a program for my dad that he can know how many hours he made at job. But I don't know how to transfert my program to a phone. Can you help me? I do so many search and I can't find anything. I think that I can't do this, so please don't juge me about this. I'm with visual studio 2022, NET8.

Sorry if my english is bad, I'm learning. I hope that you can understand. Thank you!

9 Comments
2024/11/06
22:56 UTC

2

need help withinput validation

I have this button set up to increase an int value when clicked and decrease when you press shift and the button. It then displays the amount in a label. I'm trying to figure out how to prevent it from going below 0. As I currently have it, it drops to a negative number then display the message box. Any thoughts how I can make this work?

 If OGeneralT >= 0 Then

     If My.Computer.Keyboard.ShiftKeyDown Then
         OGeneralT -= General
     Else
         OGeneralT += General
     End If

     lblOGeneral.Text = OGeneralT

 Else
     MessageBox.Show("Number can't be less than zero")
     OGeneralT = 0

 End If
7 Comments
2024/11/06
19:41 UTC

7

Hourly rate B2B contract for VB 6?

Hello VBers!
I was contacted by a recruiter from Capgemini for a mid-role I will paste some of the insights as the text is long.

I was just offered 32 euros per hour (B2B). I live in Romania and I have done a Bachelors here, and a Master's in Switzerland, but I have only a year of experience. The job is for a senior role, so I guess that I will be "sold" like that. Now I would like to counter it, and ask for more. I am thinking of 55 euros/hour (as the technology is old and many avoid it), is it too much? Now I have a very stable job as a .NET developer, but I don't earn that well, I get 1250 euros/month.

Also, if I am fired I have where to live and I have an small extra income flow, so I can still survive.

Thank you all guys, for your time to read this long text and even reply! Appreciate it.

___________________________________________________________________________________________________________

Join our dynamic team to work on a cutting-edge banking project for one of Europe’s largest financial institutions.

MAIN TASKS AND RESPONSIBILITIES

- Design, develop, and maintain backend services and APIs to support various banking

functionalities.

- Collaborate with cross-functional teams to define, design, and ship new features.

...

- 6+ years of experience in software development

- Experience with Visual Basic 6

6 Comments
2024/11/04
09:08 UTC

2

Object reference not set to an instance of an object - please help

This VB script is reading text field values being fed from a table, which are coming from an XML file. The values are constantly changing and the XML file is being re-written and the data table is constantly updating the text fields.

I keep getting an error in the application running the script. "Script 'ElectionFS_404' Error Line 7: Object reference not set to an instance of an object". The line this error is occurring is

If Input.Find("results_40").Text("Winner2Mark.Text") = "W" then

Sometimes the loop will run fine for 2 hours, other times it will error out in 3 minutes. I am about to lose my mind trying to figure out what to do with it. I assume the issue is when the XML file or data table is being updated, the text fields are temporarily blank or unavailable. If I immediately restart the script, it will run fine again for some time, then error out again on the same line. I have a couple of similar scripts that all error out on that first If line.

It doesn't seem to care if the field is empty as it errors out even when the "W" is present.

Is there a way to handle this in a way that causes it to ignore the error or start over again?

I'd appreciate any type of feedback or hints as to what I can add or subtract to stop this error. Thank you all for checking out my post. Here is the script -

Dim W, fswinmrk2, fswinmrk1, results_40, ElectionFS_40 As String

Do While True

If Input.Find("results_40").Text("Winner2Mark.Text") = "W" then
API.Function("SetMultiViewOverlay",Input:="ElectionFS_40",Value:="9,fswinmrk2")

Else If Input.Find("results_40").Text("Winner1Mark.Text") = "W" then
   API.Function("SetMultiViewOverlay",Input:="ElectionFS_40",Value:="9,fswinmrk1")

Else 
     API.Function("SetMultiViewOverlay",Input:="ElectionFS_40",Value:="9,none")

End If
Loop
10 Comments
2024/11/02
20:12 UTC

4

PrintDialog1.PrinterSettings.SupportsColor Not Working

Hi guys, I had some trouble with PrintDialog1.PrinterSettings.SupportsColor. When I set my printer with with PrintDialog1.PrinterSettings.PrinterName, I should get that the printer doesn't support colors, but it says that it does. Why? If a try to use the PrintDialog1.ShowDialog(), it knows that the printer can't use colors but the command says it can. I hate this. I even tried with the PrintDocument, it doesn't work, either. Can you guys please help me?

6 Comments
2024/11/01
15:26 UTC

2

Integers across forms

I'm trying to make a casino with multiple forms, but I don't know how to carry an integer for a money amount from one form to another (example: from the lobby form to the bar table form). Does anyone know how to do this?

2 Comments
2024/10/30
19:23 UTC

3

Crash course on VB/asp.net?

I need to quickly study source code of a working legacy project built with VB and asp.net (and a MS SQL Server db), figure out what all the core modules/procedures are and what they do, and turn it a Python FastAPI backend for a future website and mobile/desktop app. I'm a Python/JS dev and have no idea of VB or dotnet.

What would be the best way to approach this? Where should I start? Any resources that can help me with this?

17 Comments
2024/10/28
01:40 UTC

Back To Top