Categories
Concrete

How to add comments in visual basic

If you want to have certain lines of code not run, but you don’t want to delete them, you can comment them. Another reason to comment is that you want to add explanatory text.

In VBA commenting code is done by putting a ‘ (quote) either at the beginning of a line or at the point of the line where the code should be commented. The VBA editor VBA colors the line green to indicate that it’s a comment

Commenting a code block

How to add comments in visual basic

Often commenting needs be applied on a block of code. This can be a part of a (or whole) procedure that you are rewriting but you want to keep your previous version of the code – just in case. This may involve commenting quite a few lines. Spending time on putting a ‘ on front of each line is a bit a waste of time. In Code VBA there are two tools that can make your life easier when commenting lines which are described in the next paragraphs.

Comment a whole procedure

Use the Code Explorer to comment a whole procedure – as in image.

Comment a selected block of code

How to add comments in visual basic

Use the Code VBA menu to comment a block of code

  1. Select the lines to comment
  2. On the Toolbar click in the ‘Code VBA’ menu select Other &raquo Comment Lines ( Alt-COC )

If you selected commented code, the menu lets you uncomment previously commented code.

In Visual Basic, Comments are the self-explanatory notes to provide detailed information about the code which we wrote in our applications.

By using comment symbol ( ‘ ), we can comment on the code in our Visual Basic programming. The comment symbol ( ‘ ) will tell the Visual Basic compiler to ignore the text following it, or the comment.

It’s always a good practice to include the comments in your Visual Basic code to provide detailed information about the functionality like what the specific block or line of code can do and it will be a benefit for anyone else who examines the code.

In Visual Basic, we can include the comments anywhere in the program without effecting our code and the comments in Visual Basic do not affect the performance of an application because the comments won’t be compiled and executed by the compiler.

Following is the example of defining the comments in Visual Basic programming language.

‘ Show Greet Messaging

Console .WriteLine( “Welcome to Tutlane.com” )

Console .ReadLine() ‘ This method to read the commands from a console

In case, if you want to comment more than one line, use the comment symbol ( ‘ ) on each line like as shown below.

‘ Show Greet Messaging

‘ Multiple line comments

Visual Basic Comments Example

Following is the example of defining the comments in Visual Basic programming language.

‘ Calling Method to Show Greet Messaging

Console .WriteLine( “Press Any Key to Exit..” )

Console .ReadLine() ‘ This method to read the commands from a console

‘ This Method will display the welcome message

Public Sub GreetMessage()

Console.WriteLine( “Welcome to Tutlane” )

If you observe the above example, we defined multiple comments by using comment symbol ( ‘ ) to provide information about functionality.

When we execute the above Visual Basic program, we will get the result as shown below.

Welcome to Tutlane

Press Any Key to Exit..

This is how we can use the comments to provide detailed information about the functionality of our Visual Basic application.

In visual studio, we can use the following keyboard shortcuts to comment/uncomment the selected lines of code based on our requirements.

To comment keyboard shortcut is Ctrl + K, C and to uncomment keyboard shortcut is Ctrl + K, U .

You next add a comment to your code. A comment is a note that doesn’t change the way the app behaves. It makes it easier for someone who is reading your code to understand what it does. Adding comments to your code is a good habit to get into.

In C#, two forward slashes (//) mark a line as a comment. In Visual Basic, a single quotation mark (‘) is used to mark a line as a comment. After you add a comment, you test your application. It’s good practice to run and test your code frequently while you’re working on your projects, so you can catch and fix any problems early, before the code gets more complicated. This is called iterative testing.

You just built something that works, and although it’s not done yet, it can already load a picture. Before you add a comment to your code and test it, take time to review the code concepts, because you will use these concepts frequently:

When you double-clicked the Show a picture button in Windows Forms Designer, the IDE automatically added a method to your program’s code.

Methods are how you organize your code: It’s how your code is grouped together.

Most of the time, a method does a small number of things in a specific order, like how your showButton_Click() (or ShowButton_Click() ) method shows a dialog box and then loads a picture.

A method is made up of code statements, or lines of code. Think of a method as a way to bundle code statements together.

When a method is executed, or called, the statements in the method are executed in order, one after another, starting with the first one.

The following is an example of a statement.

Statements are what make your programs do things. In C#, a statement always ends in a semicolon. In Visual Basic, the end of a line is the end of a statement. (No semicolon is needed in Visual Basic.) The preceding statement tells your PictureBox control to load the file that the user selected with the OpenFileDialog component.

To add comments

Add the following comment to your code.

Use the programming language control at the top right of this page to view either the C# code snippet or the Visual Basic code snippet.

How to add comments in visual basic

Your showButton button’s Click event handler is now finished, and it works. You have started writing code, starting with an if statement. An if statement is how you tell your app, “Check this one thing, and if it’s true, do these actions.” In this case, you tell your app to open the Open File dialog box, and if the user selects a file and chooses the OK button, load that file in the PictureBox.

The IDE is built to make it easy for you to write code, and code snippets are one way it does that. A snippet is a shortcut that gets expanded into a small block of code.

You can see all of the snippets available. On the menu bar, choose Tools > Code Snippets Manager. For C#, the if snippet is in Visual C# . For Visual Basic, the if snippets are in Code Patterns > Conditionals and Loops. You can use this manager to browse existing snippets or add your own snippets.

To activate a snippet when typing code, type it and choose the Tab key. Many snippets appear in the IntelliSense window, which is why you choose the Tab key twice: first to select the snippet from the IntelliSense window, and then to tell the IDE to use the snippet. (IntelliSense supports the if snippet, but not the ifelse snippet.)

Before you run your application, save your app by choosing the Save All toolbar button, which should look similar to the following screenshot.

Save All button

Alternatively, to save your app, choose File > Save All from the menu bar (or press Ctrl+Shift+S). It’s a best practice to save early and often.

When it’s running, your program should look like the following image.

How to add comments in visual basic
Picture Viewer

To test your app

Choose the F5 key or choose the Start Debugging toolbar button.

Choose the Show a picture button to run the code you just wrote. First, the app opens an Open File dialog box. Verify that your filters appear in the Files of type drop-down list at the bottom of the dialog box. Then navigate to a picture and open it. You can usually find sample pictures that ship with the Windows operating system in your My Documents folder, inside the My PicturesSample Pictures folder.

If you don’t see any images in the Select a picture file dialog box, be sure that the All files (*.*) filter is selected in the drop-down list on the lower right side of the dialog box.

Load a picture, and it appears in your PictureBox. Then try resizing your form by dragging its borders. Because you have your PictureBox docked inside a TableLayoutPanel, which itself is docked inside the form, your picture area will resize itself so that it’s as wide as the form, and fills the top 90 percent of the form. That’s why you used the TableLayoutPanel and FlowLayoutPanel containers: They keep your form sized correctly when the user resizes it.

Right now, larger pictures go beyond the borders of your picture viewer. In the next step, you’ll add code to make pictures fit in the window.

To continue or review

To go to the next tutorial step, see Step 10: Write code for additional buttons and a check box.

This quick guide will teach you the VSCode comment shortcut and everything else you need to know about commenting in VS Code, including multi-line comments.

How to add comments in visual basic

I don’t know of a programming language that does not support comments.

Code-comments are incredibly useful. When building out complex functionality, sometimes I’ll even write out the whole function in pseudo-code comments before writing any code.

Comments make code more readable and understandable. This is especially useful if you work on a large team with lots of people. Every comment you write could save you and your colleagues some back and forth on slack.

The other great use-case of comments is quickly disabling one or multiple lines of code. This comes in handy when debugging your program.

Comments serve two main use-cases:

  • Add information that gives context to your code
  • Quickly disable code while debugging

Here’s how to do both in VS Code:

Create a Comment in VSCode, the easy way.

You’ll use this mainly to add information to the flow of your program that will help your future-self and your colleagues understand what’s going on.

First, place your cursor where you’d like to add the comment. Then, use the VS Code comment shortcut that corresponds to your platform below.

  • On Windows, the shortcut is: CTRL + /
  • On Mac, the shortcut is: Command + /

The VSCode comment shortcut Mac is very similar to the Windows version.

Comment-out code in VSCode

This is the other main usage of comments. Commenting-out code while debugging. This is probably the most useful shortcut in here. Here’s how to do it:

  1. Select the text or code that you want to comment out

How to add comments in visual basic

  1. Execute the shortcut that corresponds to your platform. (editor.action.commentLine)
  • Windows: Ctrl + /
  • Mac: Command + /

How to add comments in visual basic

You can also uncomment using the same command. Select the code that is currently commented-out and execute the shortcut. It should become un-commented again.

How to add comments in visual basic

Once you do it a few times it will become muscle memory and boost your productivity. I use this command constantly and can’t imagine not having it.

Toggling block comments in VSCode

Some programming languages support block comments. These are comments which span multiple lines of code (a block). If you want to comment out multiple lines of code within the same comment, this is what you’re looking for.

To toggle a VSCode comment block, you can use editor.action.blockComment:

  • Windows: Shift + Alt + A
  • Mac: Shift + Option + A

How to add comments in visual basic

There’s one other way to comment and un-comment, but it’s not as handy.

Comment out code (editor.action.addCommentLine):

  • Windows: Ctrl + K + C
  • Mac: Command + K + C

Un-comment code (editor.action.removeCommentLine):

  • Windows: Ctrl + K + U
  • Mac: Command + K + U

The main difference with these commands is that they each only have a single purpose. They do not toggle code like the slash shortcut. So, if you keep executing (CTRL + K + C), the comments will keep piling up, as shown in the screenshot below.

How to add comments in visual basic

The same is true for un-commenting.

Like I said, I think these commands are a lot less handy, and I don’t think there’s ever a good reason to them over the slash one. unless of course you rebound the slash shortcut to do something else.

Changing the comment key binds in VS Code

If for some reason you want to change the default key binds for commenting and uncommenting in VS Code, you can follow these steps:

Comments are used in VBE to document the purpose of the procedures, functions, logic’s, and variables. It helps other programmers can effortlessly work on the same code in future. Comments are ignored by the interpreter and compiler and does not affect performance while execution. It is good programming practice or habit to begin all procedures or functions with a comment describing what it does. When you change any existing code details (statements), remember to update comment as well what it does.

You can also add comments to your code by preceding the text with the REM keyword. However, the Single Quote (‘) symbol and the Comment or Uncomment buttons are easier to use. It occupies less space in memory. Commented line always highlight in green color in the code window.
Note: While debugging lines or statements of code we can comment temporarily. The statements can be Uncommented afterwards. It is one of a useful technique to save processing time.

How to add comments in visual basic

Here are the two methods to add comments to statements in Excel VBE
Method 1: Any line or statement starts with a Single Quote (‘) is treated as comment in VBA.
Here is the simple example for your reference.
‘Here is simple example to comment code

You can also insert a comment at the end of the statement. Please find below example.

Method 2: Any line or statement that starts with the keyword ‘REM’ is treated as comment in VBE.
Here is the simple example for your reference.

How to add comments in visual basic

The Comment Block and UnComment Block buttons on the Edit toolbar are very useful for commenting or uncommenting multiple lines of code in one shot.
Comment Block : Adds the single quote ( ‘ ) to the beginning of each line in the currently selected statements.

UnComment Block : Remove the single quote ( ‘ ) from the beginning of each line in the currently selected statements.

Excel VBA Tutorial:

Please click on below link to go back to see Excel VBA Tutorial table of content.

If you like this extention, then maybe you’d like to check Amigo

Better Comments is a Visual Studio extension that gives you the ability to customize the font and opacity of your comments independently of the editor’s font settings. It also adds four additional comment classifications, each classification with its own customizable foreground.

Features

  • Additional comment classifications. Important, Question, Task, and Crossed.
  • Customizable foreground for each comment classification.
  • Customize the font settings and opacity of your comments.
  • Works with C#, F#, VB.NET, C/C++, JavaScript, Python, HTML, and XAML.

Comment Classifications

  • Use ‘!’ for Important.
  • Use ‘?’ for Question.
  • Use “Todo” (Case ignored) for Task.
  • Use ‘x’, ‘X’, or double comment for strikethrough (Crossed).

Or you can use your own custom tokens

How to add comments in visual basic

How to add comments in visual basic

C#, F#, C/C++, and JavaScript

How to add comments in visual basic

How to add comments in visual basic

How to add comments in visual basic

HTML/XAML ( Works only with single-line comments )

How to add comments in visual basic

Multiline delimited comments ( Works only in C# ).

How to add comments in visual basic

Single-line delimited comments ( Works in C#, F#, C/C++, and JavaScript )

Custom Foreground Color for each Classification

You can set each comment classification foreground color to whatever you like.

You can also set a particular comment classification font weight to bold.

Go to Tools => Options => Fonts and Colors

How to add comments in visual basic

Independent Font Settings

You can change the comments font settings without affecting the editor’s font settings.

Visual Studio 2013 Custom Tokens – This is a feature that has been around forever. It is one that I am sure is underutilized to a great extent. So everyone probably knows about TODO comments. If you have several things that you need to do or complete, you can add a simple To-Do list in you code by adding TODO’s.

All your TODO’s will then show up in your Task List when you set the Task List to display Comments. Custom Tokens allow you to go a step further and roll your own.

Visual Studio 2013 Custom Tokens

To create your own tokens is nice because you can now customize their meaning. For example, you might want to create TODO’s for specific sections of code or you might want to logically separate different Token Items based on the work that still needs to be done. Whatever your reason, it is rather easy to do this. Go to Tools -> Options.

How to add comments in visual basic

In the search text box, type in the word ‘tokens’ and the search will filter as you type. Select the Environment -> Task List option. You will notice that there are already a few tokens in the Token List. The MSDN library has a nice explanation of the HACK, TODO and UNDONE tokens.

How to add comments in visual basic

In the Name text box, add the text you want for your new custom token. I just added this custom token because I couldn’t think of a suitable name, but you will probably find that the name of the custom token is largely decided by a specific need at the time. For now I just named mine ‘DirkTodo’.

How to add comments in visual basic

Another nice feature is that you can specify the priority of the new custom token. Obviously this will depend on the use of the token. For this example I just specified a high priority.

How to add comments in visual basic

Clicking on the ‘Add’ button will enable this custom token in Visual Studio. Something I would probably have liked to have seen is the ability to add these tokens to Intellisense.

How to add comments in visual basic

In your code window, add your custom token to a specific comment and open up your Task List.

How to add comments in visual basic

If you don’t see your Task List, you can enable it under the View menu or type Ctrl+W, T to enable the Task List.

How to add comments in visual basic

Next, change your Task List to show Comments. Mine usually defaults to User Tasks which does not display any of the custom tokens or TODO’s.

How to add comments in visual basic

You will now see that the custom token you created is listed in the Task List with a priority level of high. I simply love this feature of Visual Studio and I use it quite frequently as you can see. I do however just use TODO’s because it is quick to add in code, but sometimes a need might arise where you need to add a custom token to your code.

Then, as Zain Naboulsi pointed out, any tokens you create are not shared with other developers. This means that you will need to standardize the tokens you use and export them allowing the other developers in your company to import them.

Lastly I do have to admit that the UI isn’t the most intuitive and it seems as though it hasn’t received a lot of love from the Visual Studio team. But at the end of the day, it is functional and that i all that matters.

Visual Basic for Application can be very helpful when is used for automation in Microsoft Office (especially in Excel). But it is not well known that VBA, together with Excel, can be used in SAP systems (those accessible from SAP Logon, for example SAP ERP, SAP BW).

To start using VBA in SAP, first the SAP Scripting must be enabled. To achieve that:

  1. Open transaction RZ11.
  2. Display parameter sapgui/user_scripting.
  3. Change the value to True.
  4. Reset SAP Logon.

Now, under the Customize Local Layout button the Script Recording and Playback option is enabled.

How to add comments in visual basic

Script Recording and Playback allow user to record VB scripts in SAP, but the true power of this functionality can be reached when the script is run from Excel.

Open the Excel, go to Developer, add new module using menu Insert and inside new module add the following code:

How to add comments in visual basic

This is just the beginning and the macro doesn’t have any true functionality, but you can run this code and check the result. To do that, first login to any SAP system (you need SAP Easy Access windows), then in Excel run the code – hit F5 in VBA editor.

You should see the message:

How to add comments in visual basic

But after clicking OK, you will get the message from VBA code:

How to add comments in visual basic

Instead of message box, you can put a code to be run in SAP. For example, you can open (with VBA) a SE16 transaction and show selection screen for TCURR table. The code to achieve that:

This is just the simple example but it presents how useful can be the VBA in SAP. Another example is described in Simple Excel application with User Form blog post.

3 thoughts on “ SAP & VBA: How to start ”

Dear,
I’m quite surpised that this code works. “Aplication” takes 2 “P”….
Further, wich reference do I need to select to make this running?
Do you have more codes available?
Thansk for your help.
Stéfan

Hi Stefan, application in VBA is reserved by the Excel itself, I think that’s why something else must be used (but agree, it’s not really accurate). If you need some more example, please contact me on LinkedIn.

Comments in code might not only be some text floating around the functions, variables, and classes, but they might contain some extra semantic information. With this improvement, you can navigate through projects much faster or even organize your knowledge. In this blog post, I’ll show you two ways to add extra metadata to comments in Visual Studio.

Intro

Navigating through a large codebase might be a complicated task. It might especially be an issue when you have big projects (not to mention legacy systems) where logical parts are spread across many different files.

Visual Studio offers many tools that help with moving between headers, declarations, class hierarchies, and all references of a given symbol. But what if you’d like to put a “to-do” item? Or an extra note? Such supplementary information can not only help with quick tasks but also might build knowledge about a system.

Here are the things you might want to use to help in Visual Studio:

  • Task list
  • Hashtags (as an extra plugin)

Let’s start with the first one.

Task Lists

Visual Studio contains a feature that enables users to add metadata directly in comments. It’s called the task list. Take a look at this piece of code from my legacy project:

class ShaderProgram
<
private :
GLuint mId;
std::vector mShaders; // refactor: convert to smart pointers!
public :
// todo: implement other special member functions!
ShaderProgram();

As you can see above, I put keywords like refactor: or todo: inside comments.

Visual Studio builds an index of all comments with those special keywords and shows them in a separate window:

This is a handy way of managing simple activities or just taking some small notes for the future. What’s more, the refactor keyword is a custom marker. Visual Studio adds flexibility to set it in the environment settings.

The task list is a nice improvement! The metadata lives inside comments so that other developers can pick up the same information. Still, you cannot easily transfer custom keywords, and the task window offers only basic support. For example, it doesn’t group things (like grouping all of the to-do lines).

Is there anything better?

Hashtags in Visual Assist

For several years I’ve been a happy user of Visual Assist, which is an excellent tool for enhancing various aspects of Visual Studio (have a look at my previous blog posts here or here ). The tool also has a powerful feature called Hashtags . This is a combination of named bookmarks, the task list, and tags that you might know from social networks.

Take a look at the example from my project with extra notes:

/// creates and can build GLSL programs, #shadersSystem
class ShaderProgram
<
private :
GLuint mId;
std::vector mShaders; // #refactor convert to smart pointers
public :
/// #refactor #ruleOfZero implement other special member functions!
ShaderProgram();

As you can see, this is just regular source code, but please notice those words preceded by # . I’m using them to mark places that might be worth refactoring. For example, notes about refactoring:

std::vector mShaders; // #refactor convert to smart pointers

Or another example:

/// creates and can build GLSL programs, #shadersSystem

This time I’ve used #shadersSystem, which groups elements that are crucial to the handling of OpenGL Shaders in my animation application.

Below you can see all of the tags that are displayed in the VA Hashtags window. Similar to Visual Studio, Visual Assist scans the source code and presents the indexed data.

In the picture above, you can see lots of different tags that I put throughout the code. For example:

  • #GlutCallbacks – this refers to all callbacks that I passed to the GLUT framework (for my OpenGL Windows Application). With all of the tags grouped under one item, I can quickly move between those functions.
  • #refactor or #modernize – things to improve later.
  • Other “notes” that refer to some subsystems like #uiTweaks , #mainLoop, and others.

The screenshot also shows a considerable difference compared to the task window. The hashtags are grouped, and you can also filter them or hide them according to the project name, directory, or even a filename.

Tags are created “on the fly.” There’s no need to predefine them in some configuration window. You just type # and some extra text (you can configure the minimum length of a tag—it’s three characters by default).

Tags are stored directly in the source code, so other developers can immediately see the same information (assuming they also use Visual Assist). Such functionality can be used to create even some simple task managers when you can assign a task by the name of a developer:

// #bartekToDo: please improve this code! don’t use goto!

Here are some more things you can do with them:

  • Cross-reference other tags. You can write see:#otherTag, and Visual Assist will build an extra list per tag that you can check.
  • When you type # in Visual Assist with autocomplete tags, you can easily refer to existing hashtags.
  • When you hover over a hashtag in the hashtags window, you’ll see a tooltip with the source code that’s near the tag; this allows you to get a better orientation without actually moving to the code.
  • And many more!

Here’s a great video that summarizes the tool:

Summary

In this short blog post, I wanted to describe two tools that you can use to add extra information to comments. Having little todo: comments or additional notes can enhance your daily work and build a handy list of actions for the future, or even build up the knowledge about the system.

Depending on your preferences, you can keep those extra notes permanently in your code or just temporarily and gradually move the knowledge and to-do actions into external documentation or a task manager.

In my daily work, I prefer VA hashtags over regular bookmarks, as they are easier to use in most cases and show that extra information and structure. You can read more about VA Hashtags on their documentation page: Visual Assist Hashtags.