0% found this document useful (0 votes)
10 views4 pages

VBA Programming Examples and Functions

The document contains various examples of VBA (Visual Basic for Applications) code snippets demonstrating different programming constructs such as functions, subroutines, conditional statements (If-Else), Select Case, loops (For-Next, Do-While, Do-Until), and object methods. Each section provides a brief code example illustrating the specific concept. The examples are designed to showcase basic programming techniques in a clear and concise manner.

Uploaded by

abhimanyupandav4
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views4 pages

VBA Programming Examples and Functions

The document contains various examples of VBA (Visual Basic for Applications) code snippets demonstrating different programming constructs such as functions, subroutines, conditional statements (If-Else), Select Case, loops (For-Next, Do-While, Do-Until), and object methods. Each section provides a brief code example illustrating the specific concept. The examples are designed to showcase basic programming techniques in a clear and concise manner.

Uploaded by

abhimanyupandav4
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Function Example

Sub CATMain()

Dim Box

Box = MsgBox(Multiplication(1, 3))

End Sub

Function Multiplication(I, II)

Multiplication = I * II

End Function

================================================

Sub Routine Example

Sub CATMain()

Multiplication 1,3

End Sub

Sub Multiplication(I, II)

Dim Box

Box = MsgBox(I * II)

End Sub

=================================================

If - Else /And /Or

Sub CATMain()

Dim A,B

A =2

B =2

If (A >= 1) And (B=1) Then

MsgBox("C = 2")
MsgBox("D = 1")

Else

MsgBox (A*B)

End If

End Sub

-------------------------------------------

Sub CATMain()

Dim A,B

A =2

B =2

If (A >= 1) Or (B=1) Then

MsgBox("C = 2")

MsgBox("D = 1")

Else

MsgBox (A*B)

End If

End Sub

==============================================

Select Case Else

Sub CATMain()

Dim Input

Input = Inputbox("Enter number between 0-2:",0)

Select Case Input

Case "0"

MsgBox("Number =0")
Case "1" , "2"

MsgBox("Number>0")

Case Else

MsgBox ("Wrong input")

End select

End Sub

=============================================

For-Next Case

Sub CATMain()

Dim I, Sum

Sum=0

For I =0 To 10 Step 1

Sum = Sum + I

Next

MsgBox (Sum)

End Sub

==============================================

Do-While Case

Sub CATMain()

Dim I, Sum

Sum=0

Do While Sum < 100

Sum = Sum + I

I=I+1

Loop
MsgBox (Sum)

End Sub

===============================================

Do-Until Case

Sub CATMain()

Dim I, Sum

Sum=0

Do

Sum = Sum + I

I=I+1

Loop Until (Sum>60) Or (I>10)

MsgBox (Sum)

End Sub

===============================================

Object-Method-Class

Print document name & part name

Sub CATMain()

Dim Part

Dim Doc

Set Doc = [Link]

Set Part = [Link]

MsgBox([Link])

MsgBox([Link])

End Sub

Common questions

Powered by AI

The 'Do Until' loop runs until a specified condition becomes true, as opposed to the 'Do While' loop, which continues as long as its condition remains true. For instance, in `Do Until (Sum>60) Or (I>10)`, the loop continues executing statements inside until either 'Sum' exceeds 60 or 'I' exceeds 10, thus guaranteeing the loop's termination once the condition is satisfied . The 'Do While' loop, on the other hand, checks its condition at each iteration to determine whether it should continue running, until the specified condition is false .

Object-oriented methods, demonstrated by accessing the document and part name through `Set Doc = CATIA.ActiveDocument` and `Set Part = Doc.Part`, provide significant benefits such as encapsulation, reusability, and easier maintenance of code. By treating 'Document' and 'Part' as objects, the code can encapsulate data within these objects and access attributes, like 'Name', directly through provided methods. This promotes reusability and extendability in complex systems, as objects can be manipulated through defined methods, allowing for cleaner, more maintainable code when managing interconnected data structures .

A 'Do While' loop is preferred when the end condition is unknown because it evaluates the stopping condition in each iteration, thus offering greater flexibility for running processes until a specific requirement is met. Unlike a 'For' loop, which iterates a set number of times, `Do While Sum < 100` continues executing as long as the condition holds true, accommodating dynamic and potentially non-deterministic processes. This allows the loop to conclude once conditions are naturally met during execution, making it ideal for tasks driven by runtime criteria rather than a fixed iteration count .

The primary difference between a 'For...Next' loop and a 'Do While' loop lies in their termination conditions and flexibility. A 'For...Next' loop, such as `For I = 0 To 10 Step 1`, iterates a known or predefined number of times based on the initialization and increment statements. The loop accumulates the sum by iterating exactly 11 times, from 0 to 10 inclusive . In contrast, a 'Do While' loop continues executing as long as a specified condition is true, `Do While Sum < 100`, which means the number of iterations isn't predefined. The loop accumulates the sum until the condition 'Sum < 100' is no longer true. The 'Do While' loop stops when it no longer satisfies the condition, providing flexibility to iterate an unspecified number of times depending on runtime calculations .

The 'If-Else' structure behaves differently based on whether 'And' or 'Or' conditions are used, affecting the decision-making process. In a scenario where 'And' is used, such as `If (A >= 1) And (B = 1) Then`, both conditions must be true for the code within the 'If' block to execute. If one or both conditions are false, the 'Else' block is executed. Conversely, when 'Or' is used, e.g., `If (A >= 1) Or (B = 1) Then`, only one of the conditions needs to be true for the 'If' block to execute. This means that the presence of the 'Or' operator allows for more flexible condition checking because meeting any single condition is sufficient .

Functions and subroutines both serve to decompose tasks in programs, but they differ in their use cases and outputs. Functions, like `Function Multiplication(I, II)`, perform specific tasks and return values to calling code, facilitating operations such as mathematical computations where results are needed for further processing . Subroutines, like `Sub Multiplication(I, II)`, generally perform tasks that do not require a return value and are often used for actions or procedures, such as displaying a message box. They help organize complex programs through modularity but are mainly invoked for their operational effects rather than their outputs .

Error handling with constructs like 'Select Case' is crucial for robust user input management. It allows developers to define specific responses to valid inputs and a default case that handles unexpected or erroneous inputs, ensuring the program behaves predictably in non-ideal scenarios. For instance, in `Select Case Input`, specific cases handle valid data entries, while `Case Else` provides a catch-all for any inputs outside the defined range, such as a wrong input, prompting an informative message . This protects against errors and improves user experience by dealing gracefully with input anomalies, reducing the likelihood of software crashing due to invalid input .

The use of object properties through methods, like accessing document and part names with `Set Doc = CATIA.ActiveDocument` and `Set Part = Doc.Part`, underlines the role of encapsulation and abstraction in object-oriented programming. This approach encapsulates data and behaviors within objects, suggesting a design that promotes modularity and separation of concerns, essential for managing complex systems. By relying on methods to manipulate object properties, developers can interact with abstractions instead of direct data access, resulting in scalable, maintainable, and reusable code designs that cater to the dynamic requirements of intricate programming tasks .

The 'Select Case' structure simplifies decision-making by allowing a variable to be tested against multiple cases, which can streamline code when multiple conditions are possible. In this structure, the program executes the code block associated with the matching case. It handles unexpected inputs using a 'Case Else', which provides a catch-all for any inputs not explicitly handled by specific 'Case' entries. This feature enhances robustness by managing unexpected or erroneous user inputs, such as when the input does not fall within the anticipated range .

A 'Do Until' loop can outperform a traditional 'For' loop in scenarios where iteration limits are not known at compile-time and terminate based on runtime conditions. This flexibility is particularly advantageous in situations where a process must continue until a dynamic condition is met—such as accumulating a total until it exceeds a particular threshold, like `Sum > 60` . While 'For' loops are beneficial when the total number of iterations is known, 'Do Until' loops allow for dynamic decision-making and iteration based on conditions evaluated during execution, making them better suited for tasks where termination is data-driven rather than count-driven .

You might also like