VB6, Adding an integer to a control name in a for loop - vb6

I am currently trying you learn VB6 and came across this issue.
I wanted to loop through a for loop and adding a number to a control name.
Dim I As Integer
For I = 1 To 5
S = CStr(I)
If TextS.Text = "" Then
LabelS.ForeColor = &HFF&
Else
LabelS.ForeColor = &H80000012
End If
Next I
This S needs to be added to Text and Label so the colour will be changed without needing to use 5 If Else statements
I hope you can help me with this.

From your comment below:
What i mean is this: If Text1.text = "" Then I need this 1 to be replaced with the variable I, so the for loop can loop through my 5 textboxes and the same for my Labels.
You can't do that (look up a variable using an expression to create its name) in VB6. (Edit: While that statement is true, it's not true that you can't look up form controls using a name from an expression. See "alternative" below.)
What you can do is make an array of your textboxes, and then index into that array. The dev env even helps you do that: Open your form in the dev env and click the first textbox. Change its name to the name you want the array to have (perhaps TextBoxes). Then click the next textbox and change its name to the same thing (TextBoxes). The dev env will ask you:
(Don't ask me why I have a VM lying around with VB6 on it...)
Click Yes, and then you can rename your other textboxes TextBoxes to add them to the array. Then do the same for your labels.
Then your code should look like this:
For I = TextBoxes.LBound To TextBoxes.UBound
If TextBoxes(I).Text = "" Then
Labels(I).ForeColor = &HFF&
Else
Labels(I).ForeColor = &H80000012
End If
Next
LBound is the lowest index of the control array, UBound is the highest. (You can't use the standard LBound and Ubound that take the array as an argument, because control arrays aren't quite normal arrays.) Note also that there's no need to put I on the Next line, that hasn't been required since VB4 or VB5. You can, though, if you like being explicit.
Just make sure that you have exactly the same number of TextBoxes as Labels. Alternately, you could create a user control that consisted of a label and a textbox, and then have a control array of your user control.
Alternative: : You can use the Controls array to look up a control using a name resulting from an expression, like this:
For I = 1 To 5
If Me.Controls("Text" & I).Text = "" Then
Me.Controls("Label" & I).ForeColor = &HFF&
Else
Me.Controls("Label" & I).ForeColor = &H80000012
End If
Next
This has the advantage of mapping over to a very similar construct in VB.Net, should you migrate at some point.
Side note:
I am currently trying you learn VB6...
(tl;dr - I'd recommend learning something else instead, VB6 is outdated and the dev env hasn't been supported in years.)
VB6's development environment has been discontinued and unsupported for years (since 2008). The runtime is still (I believe) supported because of the sheer number of apps that use it, although the most recent patch seems to be from 2012. But FWIW, you'd get a better return on your study time learning VB.net or C#.Net (or any of several non-Microsoft languages), rather than VB6...

Related

Scripting Word from vbs

I'm trying to get Word to fill in cells in a table. The script works when run as a macro from within Word, but fails when saved as a .vbs file and double-clicked, or run with wscript. This is a part of it.
set obj = GetObject(,"Word.Application)
With obj
With .Selection
MsgBox .text
If (.Information(wdWithInTable) = True) Then
.Collapse Direction:=wdCollapseStart
tCols = .Tables(1).Columns.Count
tRow = .Information(wdStartOfRangeRowNumber)
tCol = .Information(wdStartOfRangeColumnNumber)
For I = 2 To 5
.Tables(1).Cell(tRow, I).Range.Text = "fred" & Str(I)
Next
` now make new row
For I = 1 To tCols - tCol + 1
.MoveRight unit:=wdCell
Next
End If
End With
End With
I have three problems. First, it won't compile unless I comment out the .Collapse and .MoveRight lines. Second, although the MsgBox .text displays the selected text, I get "out of range" errors if I try to access any .Information property.
I'm sure I'm missing something very simple: I usually write software for Macs, and I'd do this using AppleScript. This is my first attempt at getting anything done under Windows.
VBScript and VBA are different languages.
They are a bit similar, but not very. Moreover, VBScript is not like AppleScript; it doesn't let you easily interface with running programs.
The interfaces you'll get from VBScript can behave subtly differently in VBA and VBScript. However, I think you've got two problems here:
:= is invalid syntax in VBScript; you'll need to find an alternative way of calling the function. Try just using positional arguments.
You've no guarantee that this will open the expected file; there could be another instance of Word that it's interacting with instead.
Since your code is not running within the Word environment it would require a reference to the Word object library in order to use enumeration constants (those things that start with wd).
VBScript, however, cannot work with references, which means the only possibility is to use the long value equivalents of the enumerations. You'll find these in the Word Language References. Simplest to use is probably the Object Browser in Word's VBA Editor. (In Word: Alt+F11 to open the VBA Editor; F2 to start the Object Browser; type in the term in the "Search" box, click on the term, then look in the bottom bar.)
The code in the question uses, for example:
wdWithInTable
wdCollapseStart
wdStartOfRangeRowNumber
wdStartOfRangeColumnNumber
wdCell
The reason you get various kinds of errors depends on where these are used.
Also, VBScript can't used named parameters such as Unit:=. Any parameters must be passed in comma-delimited format, if there's more than one, in the order specified by the method or property. If there are optional parameters you don't want to use these should be left "blank":
MethodName parameter, parameter, , , parameter

Export validation rules from Microsoft Access mdb file

I have an MDB file which contains a number of tables and forms. Each field has a validation rule such as Is Null Or >=0 And <=255.
This access database is being converted into an online system using MySQL. Exporting all the data is easy using MDBTools (https://github.com/brianb/mdbtools).
However I can't find any way of exporting the validation rules. There are thousands of fields across over 100 tables so it's going to be important to export and import them rather than rewrite each one.
I don't really mind what format they're exported in, any sort of text format so I could do a regular expression or something will be fine.
However I haven't been able to find any information anywhere on exporting these validation rules.
Perhaps if it's not built into access by default then a VB script could be used to find the info and write it to a text file? I'm not really familiar with access or windows at all so if anyone could suggest if that was a possibility that would be great.
Using VBA allows you to retrieve field validation rules directly.
I realize it's probably too late to help you now. And, although it may not seem appropriate for someone unfamiliar with Access and VBA, this approach requires only a table, copying the code below into a standard module, and running it. So someone else may benefit.
I created my table, field_validation_rules, to store the text of the validation rule properties. The table includes 3 text fields: table_name; field_name; and validation_rule.
Public Sub GatherValidationRules()
Dim db As DAO.Database
Dim fld As DAO.Field
Dim rs As DAO.Recordset
Dim tdf As DAO.TableDef
Set db = CurrentDb
Set rs = db.OpenRecordset("field_validation_rules", dbOpenTable, dbAppendOnly)
For Each tdf In db.TableDefs
If Not (tdf.Name Like "~*" Or tdf.Name Like "MSys*") Then
For Each fld In tdf.Fields
If Len(fld.ValidationRule) > 0 Then
rs.AddNew
rs!table_name.Value = tdf.Name
rs!field_name.Value = fld.Name
rs!validation_rule.Value = fld.ValidationRule
rs.Update
End If
Next
End If
Next
rs.Close
End Sub
The ValidationRule property is a string value. If the property has not been assigned for a given field, ValidationRule is an empty string. The code skips those, storing only validation rules for fields which have them assigned.
If you want the collected validation rules in a text file, there a several options. I dumped mine to CSV like this:
DoCmd.TransferText acExportDelim, , "field_validation_rules", "C:\share\Access\field_validation_rules.txt", False
To anyone else finding this, this is how I wound up doing it. This was in Access 2003, it may be different in other versions.
First I went to Tools > Analyze > Documenter selected the table I wanted and used these settings:
I was then presented with what looked like a pdf or word doc (I don't think it is, but it doesn't really matter).
I then did File > Export and selected "Text Files .txt" and saved it to a location on my computer.
I then opened the .txt file in PHP (anywhere you can do regular expressions should be fine).
In my instance not every single field had validation rules and the validation rules did not appear if they were not set, which meant a regular expression to fetch the fieldID had more results than to fetch the validation rules.
So I used two regular expressions.
/SourceField:\s+(\S+).*?AllowZeroLength/msi
This gets everything betwenen SourceField and AllowZeroLength. AllowZeroLength is the first bit of repeating text after the validation rules.
I then used this regular expression to get the validation rules from within that string.
/ValidationRule:\s+(.*)\\r/
I had to use \r instead of new line, probably something to do with moving it from Windows to Ubuntu.
In PHP it looked like this:
<?php
$file_contents = file_get_contents('validations.txt');
$response = [];
preg_match_all('/SourceField:\s+(\S+).*?AllowZeroLength/msi', $file_contents, $matches);
for($i = 0; $i < count($matches[0]); $i++) {
$id = $matches[1][$i];
preg_match('/ValidationRule:\s+(.*)\\r/', $matches[0][$i], $validation_match);
$response[$id] = $validation_match[1] ?? null;
}
There is almost certainly a cleaner regular expression than this, but this was incredibly quick and I got exactly what I wanted.

Missing events in properties for VB6

I am a self taught amateur Visual Basic programmer. My programs are for myself, friends and some non-profit organizations. I have a situation that I thought would be reasonably simple but doesn't seems the case.
I have a text box array of 6 elements (1 -6) named "txtBilled" .When the value is entered into any but element 6 I want to add the values in 1-5 and put result in element 6. My problems start due to the fact that the properties for the text array does not provide for a lost focus option. Searching the inter provides statements that this is normal, others say the "Lost Focus" should always be there.
As a second approach I tried to use the validate element. Never used this before created a sub as follows that I found on the web.
Private sub txtBilled__Validate(Cancel as Boolean)
Found that the Validate event is also not included in the properties for the array
I am using VB6 version 8176 under Windows 10.
Any ideal as to what I am doing incorrectly would be appreciated.
Can you not create your own LostFocus sub using the Index of the textbox array?
Private Sub txtBilled_LostFocus(Index As Integer)
Dim i As Integer
dim sngTotal As Single
' Calculate sum only if not in last textbox
If Index <> uBound(txtBilled) Then
For i = LBound(txtBilled) to UBound(txtBilled) - 1
sngTotal = sngTotal + txtBilled(i)
Next i
txtBilled(uBound(txtBilled)) = sngTotal
End If
End Sub

How do I center text of a cell vertically in a table using VBScript and a word document?

I tried using
With myTable.Rows(1)
.Height = 20
.Cells.VerticalAlignment = wdAlignVerticalTop
End With
But it doesn't seem to work for VBScript, does someone know how to do what I want to do?
If you are using vbscript, then vbscript does not know the values of your word enumerated constants. So, either assign values to these constants or just use the numbers/constants directly as shown below:
With myTable.Rows(1)
.Height = 20
.Cells.VerticalAlignment = 1 '1 means WdCellVerticalAlignment(see link below)
End With
Click here -- Word Enumerated constants
Also, If you are using Word VBA and not vbscript, then you should mention the correct enumerated constant. In your case, It should not be wdAlignVerticalTop. Instead, it should be WdCellVerticalAlignment.

What's so bad about using button captions as variables in VB6?

I received some justified critical feedback on my last question (How to gracefully exit from the middle of a nested subroutine when user cancels?) for using the caption of a command button as a state variable. I did it because it's efficient, serving two or three purposes at once with very little code, but I understand how it could also cause problems, particularly in the slightly sloppy way I originally presented it.
I feel like this deserves its own discussion, so here's the same idea cleaned up a bit and modified to do it "right" (which basically means defining the strings in a single place so your code won't start failing because you simply changed the text of a command button). I know my variable and control naming convention is poor (OK, nonexistent), so apologies in advance. But I'd like to stay focused on the caption as state variable discussion.
So here we go:
' Global variables for this form
Dim DoTheThingCaption(1) As String
Dim UserCancel, FunctionCompleted As Boolean
Private Sub Form_Initialize()
' Define the possible captions (is there a #define equivalent for strings?)
DoTheThingCaption(0) = "Click to Start Doing the Thing"
DoTheThingCaption(1) = "Click to Stop Doing the Thing"
' Set the caption state when form initializes
DoTheThing.Caption = DoTheThingCaption(0)
End Sub
Private Sub DoTheThing_Click() ' Command Button
If DoTheThing.Caption = DoTheThingCaption(0) Then
UserCancel = False ' this is the first time we've entered this sub
Else ' We've re-entered this routine (user clicked on button again
' while this routine was already running), so we want to abort
UserCancel = True ' Set this so we'll see it when we exit this re-entry
DoTheThing.Enabled = False 'Prevent additional clicks
Exit Sub
End If
' Indicate that we're now Doing the Thing and how to cancel
DoTheThing.Caption = DoTheThingCaption(1)
For i = 0 To ReallyBigNumber
Call DoSomethingSomewhatTimeConsuming
If UserCancel = True Then Exit For ' Exit For Loop if requested
DoEvents ' Allows program to see GUI events
Next
' We've either finished or been canceled, either way
' we want to change caption back
DoTheThing.Caption = DoTheThingCaption(0)
If UserCancel = True Then GoTo Cleanup
'If we get to here we've finished successfully
FunctionCompleted = True
Exit Sub '******* We exit sub here if we didn't get canceled *******
Cleanup:
'We can only get to here if user canceled before function completed
FunctionCompleted = False
UserCancel = False ' clear this so we can reenter later
DoTheThing.Enabled = True 'Prevent additional clicks
End Sub '******* We exit sub here if we did get canceled *******
So there it is. Is there still anything really that bad about doing it this way? Is it just a style issue? Is there something else that would give me these four things in a more desirable or maintainable way?
Instant GUI feedback that user's button press has resulted in action
Instant GUI feedback in the location where user's eyes already are on how to CANCEL if action is not desired
A one-button way for users to start/cancel an operation (reducing the amount of clutter on the GUI)
A simple, immediate command button disable to prevent multiple close requests
I can see one concern might be the close coupling (in several ways) between the code and the GUI, so I could see how that could get to be a big problem for large projects (or at least large GUIs). This happens to be a smaller project where there are only 2 or 3 buttons that would receive this sort of "treatment".
The single biggest problem with this technique is that it uses a string as a boolean. By definition, a boolean variable can have only two states, while a string can have any number of states.
Now, you've mitigated the danger inherent in this somewhat by relying on an array of predefined strings to define allowed values for the command button text. This leaves a handful of lesser issues:
Logic is less-than-explicit regarding current and available states (there are actually four possible states for the form: not-started, started, completed, started-but-canceling) - maintenance will require careful observation of the potential interactions between button text and boolean variable states to determine what the current state is / should be. A single enumeration would make these states explicit, making the code easier to read and understand, thereby simplifying maintenance.
You're relying on the behavior of a control property (button text) to remain consistent with that of the exposed property value type (string). This is the sort of assumption that makes migrating old VB6 code to newer languages / platforms absolute hell.
String comparison is much, much slower than a simple test of a boolean variable. In this instance, this won't matter. In general, it's just as easy to avoid it.
You're using DoEvents to simulate multi-threading (not directly relevant to the question... but, ugh).
The biggest issue i've come accross when working on (very old) code like this [button captions as variables] is that globalisation is a nightmare.... I had to move a old vb6 app to use English and German... it took weeks, if not months.
You're using goto's as well..... a bit of refactoring needed perhaps to make the code readable??
**Edit in response to comments
I'd only use a goto in vb6 at the top of each proc;
on error goto myErrorHandler.
then at the very bottom of the proc i'd have a one liner that would pass err to a global handler, to log the error.
Ignoring the general architecture/coupling problems because you are aware of those issues, one problem with your approach is because VB6 controls do magic stuff when you set properties.
You may think you are just setting a property but in many cases you are causing events to fire also. Setting a checkbox value to true fires the click event. Setting the tabindex on a tab control causes a click event. There are many cases.
If I remember correctly I also think there are scenarios where if you set a property, and then read it immediately, you will not see the update. I believe a screen refresh has to occur before you see the new value.
I have seen too much horrible VB6 code that uses control properties as storage. If you ever find this kind of code you will recognize it because it is scattered with redundant calls to Refresh methods, DoEvents and you will frequently see the UI get hung. This is often caused by infinite loops where a property is set, an event is fired and then another property is set and eventually someone writes a line of code that updates the first property again.
If those issues don't scare you enough then think of this. Some of us just are not that smart. I've been coding in VB6 for over 10 years and have personally written probably around 750K LOC and I keep staring at your example above and I find it very difficult to understand what it going on. Assume that all the people that will need to read your code in the future will be really dumb and make us happy by writing really simple looking code.
I think it's better to decouple the caption text from the state of processing. Also the goto's make it hard to read. Here is my refactored version...
Private Const Caption_Start As String = "Click to Start Doing the Thing"
Private Const Caption_Stop As String = "Click to Stop Doing the Thing"
Private Enum eStates
State_Initialized
State_Running
State_Canceled
State_Completed
End Enum
Private Current_State As eStates
Private Sub Form_Initialize()
DoTheThing.Caption = Caption_Start
Current_State = State_Initialized
End Sub
Private Sub DoTheThing_Click()
If Current_State = State_Running Then
'currently running - so set state to canceled, reset caption'
'and disable button until loop can respond to the cancel'
Current_State = State_Canceled
DoTheThing.Caption = Caption_Start
DoTheThing.Enabled = False
Else
'not running - so set state and caption'
Current_State = State_Running
DoTheThing.Caption = Caption_Stop
'do the work'
For i = 0 To ReallyBigNumber
Call DoSomethingSomewhatTimeConsuming
'at intervals check the state for cancel'
If Current_State = State_Canceled Then
're-enable button and bail out of the loop'
DoTheThing.Enabled = True
Exit For
End If
DoEvents
Next
'did we make it to the end without being canceled?'
If Current_State <> State_Canceled Then
Current_State = State_Completed
DoTheThing.Caption = Caption_Start
End If
End If
End Sub
Apart from removing the GOTos as DJ did in his answer, there is nothing really wrong about your approach. The button caption can have only two states, and you use those two states to define the flow in your code.
I have however two reasons why I would do it differently:
Your method creates problems when you want to translate your program into a different language (in my experience you should always plan for that), because the captions would change in another language
It goes against the principle of seperating the user interface from the program flow. This may not be an important thing for you, but when a program gets bigger and more complex, having a clear seperation of the UI from the logic makes things much easier.
To sum it up, for the case at hand your solution certainly works, and there is no reason why it shouldn't. But on the other hand experience has taught us that with more complex programs, this way can cause problems which you can easily avoid by using a slightly different approach.
Also, I think it is safe to assume that everybody who criticised your example did so because they made a simnilar choice at some point, and later realised that it was a mistake.
I know I did.
This ties your underlying algorithm to specific behavior in your UI. Now, if you want to change either one of them, you have to make changes to both. As your app grows in size, if you don't keep your changes local by encapsulating logic, maintenance will become a nightmare.
If anyone for any reason ever needs to work on your code, they won't find practices and conventions they are familiar and comfortable with, so the boundaries of functionality won't exist. In other words, you are headed in the wrong direction on the Coupling/Cohesion trail. Functionally integrating State management with the UI is the classic poster child for this issue.
Do you understand OOP at all? (Not a criticism, but a legitimate question. If you did, this would be a lot clearer to you. Even if it's only VB6 OOP.)
Localization has the biggest impact on the type of logic OP is presenting. As several people mentioned it - what if you need to translate the app into Chinese? And German? And Russian?
You'd have to add additional constants covering those languages too... pure hell. GUI data should remain what it is, a GUI data.
The method OP describes here reminded me what Henry ford said: "Any customer can have a car painted any color that he wants so long as it is black".

Resources