• 0

[VB6] Boolean Function


Question

What needs to be changed or added for the following code to work? I program mostly in Java now, and I've forgotten alot of my Visual Basic.

Option Explicit

Private Sub cmdEncode_Click()

    Dim key1 As String
    Dim key2 As String
    
    key1 = UCase(txtKey1.Text)
    key2 = UCase(txtKey2.Text)
    
    If ValidateKey(key1, "Validating key 1...", "Key 1 not valid!") = False Then
        Exit Sub
    End If
    
    If ValidateKey(key2, "Validating key 2...", "Key 2 not valid!") = False Then
        Exit Sub
    End If
    
    Dim i As Integer
    
   
    For i = 1 To Len(key1)
        ProgressBar.Value = i

        Dim x As Integer
        For x = 0 To i - 1
            If lblKey1(x).Caption <> Mid(key1, i, 1) Then
                lblKey1(i - 1).Caption = Mid(key1, i, 1)
            End If
        Next x
    Next i
    
    
End Sub

Private Function ValidateKey(ByVal key As String, ByVal status As String, ByVal error As String) As Boolean
    
    Dim check(Len(key)) As String
    Dim i As Integer
    
    lblStatus.Caption = status
    ProgressBar.Min = 1
    ProgressBar.Max = Len(key)

    
    For i = 1 To Len(key)
        ProgressBar.Value = i
    
        Dim x As Integer
        For x = 0 To i - 1
            If check1(x) <> Mid(key, i, 1) Then
                check1(i - 1) = Mid(key, i, 1)
            Else
                ProgressBar.Value = 0
                lblStatus.Caption = error
                ValidateKey = False
                Exit Function
            End If
        Next x
    Next i
    
    ValidateKey = True
End Function

This throws the following error:

  Quote
Compile error:

Constant expression required

When you follow the debug it takes you to these lines:

Private Function ValidateKey(ByVal key As String, ByVal status As String, ByVal error As String) As Boolean
    
    Dim check(Len(key)) As String

It highlights the function with yellow and then selects the text "key" in "Len(key)" as the source of the error.

Link to comment
https://www.neowin.net/forum/topic/398028-vb6-boolean-function/
Share on other sites

15 answers to this question

Recommended Posts

  • 0

Alright, that worked beautifully! Thank you. I have another problem. This code does not do what it is supposed to do! >:-( I'm trying to scan a word to make sure that a letter is only used once in the whole string. If anyone can see why this code doesn't work, your help would be appreciated!

EDIT: Nevermind, very simple logic mistake, just had to change the order of the if and the second for loop! Thanks again for the help!

Edited by Delox
  • 0

Once again, it was a simple mistake. I have a new problem with a sub routine. I'm trying to make it fill the remaining labels in a row with letters from the alphabet that are not used. So far the program looks like this:

Option Explicit

Private Sub cmdEncode_Click()

    Dim key1 As String
    Dim key2 As String
    
    key1 = UCase(txtKey1.Text)
    key2 = UCase(txtKey2.Text)
    
    If ValidateKey(key1, "Validating key 1...", "Key 1 not valid!") = False Then
        Exit Sub
    End If
    
    If ValidateKey(key2, "Validating key 2...", "Key 2 not valid!") = False Then
        Exit Sub
    End If
    
    Dim i As Integer
    
    ProgressBar.Min = 0
    ProgressBar.Max = Len(key1)
    lblStatus.Caption = "Assigning headers..."
    For i = 1 To Len(key1)
        ProgressBar.Value = i

        Dim x As Integer
        For x = 0 To i - 1
            If lblKey1(x).Caption <> Mid(key1, i, 1) Then
                lblKey1(i - 1).Caption = Mid(key1, i, 1)
            End If
        Next x
    Next i
    
    Call finishRow(-1, i)
    
    lblStatus.Caption = "Done!"
End Sub

Private Sub finishRow(ByVal row As Integer, ByVal pos As Integer)
    ProgressBar.Min = pos
    ProgressBar.Max = UBound(lblKey1) - pos
    lblStatus.Caption = "Assigning headers..."
    
    Dim asc As Integer
    asc = asc("A")
    
    If row = -1 Then
        Dim i As Integer
        
        For i = pos To 25
            ProgressBar.Value = i
            Dim x As Integer
            
            For x = 0 To i
                If asc = lblKey1(x) Then
                    asc = asc + 1
                End If
            Next x
            
            lblKey1(i).Caption = Chr(asc)
        Next i
    End If
End Sub

Private Function ValidateKey(ByVal key As String, ByVal status As String, ByVal error As String) As Boolean
    ProgressBar.Value = 0
    
    If Len(key) = 0 Then
        ProgressBar.Value = ProgressBar.Max
        lblStatus.Caption = error
        ValidateKey = False
        Exit Function
    End If
    
    Dim check() As String
    ReDim check(Len(key))
    
    Dim i As Integer
    
    For i = 1 To Len(key)
        check(i - 1) = Mid(key, i, 1)
    Next i
    
    lblStatus.Caption = status
    ProgressBar.Min = 0
    ProgressBar.Max = Len(key)

    
    For i = 0 To Len(key)
        ProgressBar.Value = i
        
        Dim x As Integer
        For x = 0 To i - 1
            Dim s As String
            
            s = Mid(key, i, 1)
            If asc(s) < asc("A") Or asc(s) > asc("Z") Then
                ProgressBar.Value = ProgressBar.Max
                lblStatus.Caption = error
                ValidateKey = False
                Exit Function
            End If
            
            If x <> i - 1 And check(x) = s Then
                ProgressBar.Value = ProgressBar.Max
                lblStatus.Caption = error
                ValidateKey = False
                Exit Function
            End If
        Next x
    Next i
    
    ValidateKey = True
    
End Function

Private Sub Form_Load()
    Dim i As Integer
    Dim c As Integer
    
    c = asc("A")
    
    For i = 0 To 25
        lblKey1(i).Caption = Chr(c)
        c = c + 1
    Next i
    
    For i = 0 To 9
        lblRow(i).Caption = i
    Next i
End Sub

At this point:

Private Sub finishRow(ByVal row As Integer, ByVal pos As Integer)

it shows the error:

  Quote
Compile error:

Expected array

Once again, I have no idea what the problem is. I haven't used Visual Basic 6 in a while...

  • 0

For i = pos To 25

ProgressBar.Value = i

Dim x As Integer

For x = 0 To i

If asc = lblKey1(x) Then

asc = asc + 1

End If

Next x

lblKey1(i).Caption = Chr(asc)

Next i

looks a little dodgy, you're comparing an int asc to a label control for equality? (Don't rely on default props)

asc never gets reset in any of the loops. Is this correct? :unsure

  • 0

asc doesn't need to be reset, as this part of the code only runs once. There will be an else section here where it will figure out which row the user is at, and use a second (10 letter) keyword to shift the alphabetical letters as far right as that postion, and print the alphabet from that point on, looping back to A, like this:

key 1 = nosamechr

key 2 = chrnotsame (this key MUST be 10 letters, which will be added later)

I need to create a table like this one below:

   | N O S A M E C H R B D F G I J K L P Q T U V W X Y Z
--+----------------------------------------------------
0 | C D E F G H I J K L M N O P Q R S T U V W X Y Z A B
1 | H I J K L M N O P Q R S T U V W X Y Z A B C D E F G
2 | R S T U V W X Y Z A B C D E F G H I J K L M N O P Q
3 | N O P Q R S T U V W X Y Z A B C D E F G H I J K L M
4 | O P Q R S T U V W X Y Z A B C D E F G H I J K L M N
5 | T U V W X Y Z A B C D E F G H I J K L M N O P Q R S
6 | S T U V W X Y Z A B C D E F G H I J K L M N O P Q R
7 | A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
8 | M N O P Q R S T U V W X Y Z A B C D E F G H I J K L
9 | E F G H I J K L M N O P Q R S T U V W X Y Z A B C D

A call to the sub finishRow(ByVal row As Integer, ByVal pos As Integer) which is "finishRow(-1, i) should complete the first line of letters (row X). I will latter add code to scan a word, take each letter and assign it to a row. It will start the alphabet from that letter, and then complete the row. Row 2 for example starts with "R" the alphabet is then finished and it loopes back to the start to complete the row.

Hopefully this will help you understand what I'm trying to accomplish. If you can think of a better way of doing this, any help would be appreciated!

  • 0

Here is the code to produce the grid using two keys ( I think this is what you want!)

I have sent the output to a text box for brevity but you could build a two dimensional array and then populate labels or create labels dynamicaly

Hope it makes sense:

Option Explicit

Private mAlphabet(25) As String

Private Sub BuildAlphabet()

Dim i As Integer

For i = 0 To 25

mAlphabet(i) = Chr(CLng(Asc("A") + i))

Next i

End Sub

Private Function BuildHeaderLine(key As String) As String

Dim ret As String

Dim i As Integer

ret = key

For i = 0 To 25

If InStr(1, key, mAlphabet(i)) = 0 Then

ret = ret & mAlphabet(i)

End If

Next i

BuildHeaderLine = ret

End Function

Private Function BuildLine(letter As String) As String

Dim ret As String

ret = letter

Dim startPos As Integer

startPos = Asc(letter) - Asc("A") + 1

Dim i As Integer

For i = startPos To startPos + 24

ret = ret & mAlphabet(i Mod 26)

Next i

BuildLine = ret

End Function

Private Sub Command1_Click()

Dim key1 As String

Dim key2 As String

key1 = UCase("nosamechr")

key2 = UCase("chrnotsame")

Call BuildAlphabet

Text1.Text = BuildHeaderLine(key1) + vbCrLf

Dim i As Integer

Dim letter As String

For i = 1 To Len(key2)

letter = Mid$(key2, i, 1)

Text1.Text = Text1.Text + BuildLine(letter) + vbCrLf

Next i

End Sub

  • 0

I've got to admit, you used some techniques there I would have never thought of! Using inStr to see if a character is used should have been obvious. The real genious is in using modulus to figure out the characters to complete the lines.

I have few more questions though:

How exactly would you go about putting this information into an array?? What I need to be able to do is reference a letter in the body using it's row number and the letter in the header for the column, as is seen on this page. It should be simple once I know how to create the table, either in memory, or as an actual table using label boxes. Any thoughts?

  • 0

Option Explicit

Private mAlphabet(25) As String


Private mOutputTable(10, 25) As String


Private Sub BuildAlphabet()
Dim i As Integer
    For i = 0 To 25
        mAlphabet(i) = Chr(CLng(Asc("A") + i))
    Next i

End Sub

Private Function BuildHeaderLine(key As String) As String
Dim ret As String
Dim i As Integer

    ret = key
    
    For i = 0 To 25
        If InStr(1, key, mAlphabet(i)) = 0 Then
            ret = ret & mAlphabet(i)
        End If
    Next i
    

    BuildHeaderLine = ret
End Function

Private Function BuildLine(letter As String, lineNo As Integer) As String
    Dim ret As String
    
    ret = letter
    mOutputTable(lineNo, 0) = letter
    
    
    Dim startPos As Integer
    
    startPos = Asc(letter) - Asc("A") + 1
    
    Dim i As Integer
    
    For i = startPos To startPos + 24
        mOutputTable(lineNo, i - startPos + 1) = mAlphabet(i Mod 26)
        ret = ret & mAlphabet(i Mod 26)
    Next i
    
    BuildLine = ret
End Function


Private Sub LetterAtPos(lineNumber As Integer, col As String, key As String)
Dim letter As String
Dim letterPos As Integer

    letterPos = InStr(1, key, col) - 1
    
    If letterPos > -1 Then
        letter = mOutputTable(lineNumber, letterPos)
        Call MsgBox("Letter Is: " + letter)
    Else
        Call MsgBox("Error")
    End If

End Sub



Private Sub Command1_Click()
    
    Dim key1 As String
    Dim key2 As String
    Dim columnKey As String
    
    key1 = UCase("nosamechr")
    key2 = UCase("chrnotsame")
    
    Call BuildAlphabet
    columnKey = BuildHeaderLine(key1)
    Text1.Text = columnKey + vbCrLf
    Text1.Text = Text1.Text + String(26, "=") + vbCrLf

Dim i As Integer
Dim j As Integer
Dim letter As String

    For i = 1 To Len(key2)
        letter = Mid$(key2, i, 1)
        Call BuildLine(letter, i - 1)
    Next i
    
    For i = 1 To Len(key2)
        For j = 0 To 25
            Text1.Text = Text1.Text + mOutputTable(i - 1, j)
        Next j
        Text1.Text = Text1.Text + vbCrLf
    Next i
    
    Call LetterAtPos(5, "R", columnKey)


End Sub

Should do it for you

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • Is this for Black people only? You'd definitely think so from the ad.
    • I have it as an icon in the Start Menu. Close enough for when I need it.
    • Windows 11 Pro with a copy of Office 2021 Pro drops to all-time low price by Steven Parker Today's highlighted deal comes via our Apps + Software section of the Neowin Deals store, where you can save 86% on Windows 11 Pro (for 2 devices) + Microsoft Office Pro 2021. Upgrade your computing experience with Windows 11 Pro. This cutting-edge operating system boasts a sleek new design and advanced tools to help you work faster and smarter. From creative projects to gaming and beyond, Windows 11 delivers the power and flexibility you need to achieve your goals. With a focus on productivity, the new features are easy to learn and use, enhancing your workflow and efficiency. Whether you're a student, professional, gamer, or creative, Windows 11 Home has everything you need to take your productivity to the next level. New interface. easier on the eyes & easier to use Biometrics login*.Encrypted authentication & advanced antivirus defenses DirectX 12 Ultimate. Play the latest games with graphics that rival reality. DirectX 12 Ultimate comes ready to maximize your hardware* Screen space. Snap layouts, desktops & seamless redocking Widgets. Stay up-to-date with the content you love & the new you care about Microsoft Teams. Stay in touch with friends and family with Microsoft Teams, which can be seamlessly integrated into your taskbar** Wake & lock. Automatically wake up when you approach and lock when you leave Smart App Control. Provides a layer of security by only permitting apps with good reputations to be installed Windows Studio Effects. Designed with Background Blur, Eye Contact, Voice Focus, & Automatic Framing Touchscreen. For a true mouse-less or keyboard-less experience TPM 2.0. Helps prevent unwanted tampering Windows 11 Pro also includes a number of productivity-focused features, such as the ability to snap multiple windows together and create custom layouts, improved voice typing, and a new, more powerful search experience. Personal and professional users will enjoy a modern and secure computing experience, with improved performance and productivity features to help users get more done. Only on Windows 11 Pro If you require enterprise-oriented features for your daily professional tasks, then Windows 11 Pro is a better option. Set up with a local account (only when set up for work or school) Join Active Directory/Azure AD Hyper-V Windows Sandbox Microsoft Remote Desktop BitLocker device encryption Windows Information Protection Mobile device management (MDM) Group Policy Enterprise State Roaming with Azure Assigned Access Dynamic Provisioning Windows Update for Business Kiosk mode Maximum RAM: 2TB Maximum no. of CPUs: 2 Maximum no. of CPU cores: 128 Good to know: Length of access: lifetime Redemption deadline: redeem your code within 30 days of purchase Access options: desktop Max number of device(s): 2 (Use one activation key for up to 2 devices) Version: Windows 11 Pro Updates included Click here to verify Microsoft partnership For Windows 10 or Newer! Get All Essential Microsoft Apps for Your PC with This One-Time Purchase This is intended for families and small businesses who want classic Office apps and email. It includes Word, Excel, PowerPoint, Outlook, Teams, and OneNote. A one-time purchase installed on 1 Windows PC for use at home or work. Lifetime license for MS Word, Excel, PowerPoint, Outlook, Teams, & OneNote One-time purchase installed on 1 Windows PC for use at home or work Instant Delivery & Download – access your software license keys and download links instantly Free customer service – only the best support! Microsoft Office Professional 2021 (for Windows) includes: Microsoft Office Word Microsoft Office Excel Microsoft Office PowerPoint Microsoft Office Outlook Microsoft Office Teams Microsoft Office OneNote Microsoft Office Publisher Microsoft Office Access Good to know: ONE-TIME PURCHASE INSTALLED ON 1 DEVICE Redemption deadline: redeem your code within 30 days of purchase Access options: desktop Full versions No subscriptions – no monthly/annual fees Version: 2021 Updates included Here's the deal: This Microsoft Office Pro 2021 + Windows 11 Pro normally costs $438, but this deal can be yours from just $54.97, that's a saving of $383. For full terms, specifications, and license info please click the link below. Use MSO5 when checking out for additional $5 off. Coupon Expires June 29. Get Microsoft Office Pro 2021 + Windows 11 Pro for just $49.97, or learn more Although priced in U.S. dollars, this deal is available for digital purchase worldwide. We post these because we earn commission on each sale so as not to rely solely on advertising, which many of our readers block. It all helps toward paying staff reporters, servers and hosting costs. Other ways to support Neowin Whitelist Neowin by not blocking our ads Create a free member account to see fewer ads Make a donation to support our day to day running costs Subscribe to Neowin - for $14 a year, or $28 a year for an ad-free experience Disclosure: Neowin benefits from revenue of each sale made through our branded deals site powered by StackCommerce.
    • I'm not a fan of the HP "Smart" app either, but it does work. I just wish I didn't have to log in to use it. HP Color LaserJet Pro MFP 4301
    • FocusOn Image Viewer 1.32 by Razvan Serea FocusOn Image Viewer is a fast, lightweight, and user-friendly photo viewer for Windows. It supports various image formats, offers basic editing tools, EXIF data display, and batch renaming. With a clean interface, slideshow mode, and easy navigation, it’s ideal for quickly viewing and organizing photos without unnecessary complexity or system resource usage. FocusOn Image Viewer key features: Auto Organize: Automatically sorts photos by date using your chosen template. Explorer View: Browse and manage images with thumbnails; includes basic edits like resize and rotate. Photo Editing: Crop, apply filters, correct colors, add borders or text. Non-Destructive Edits: Original images remain untouched. Photo Sharing: Post directly to blogs, Twitter, and Facebook. Email Support: Send selected images via email. Print Options: Print to fit paper size, preserve aspect ratio, or fit multiple images per page. Slideshow: View selected photos in a slideshow. EXIF Tools: View or remove EXIF data. Scanning: Import from TWAIN or WIA-compatible scanners. Set as Background: Quickly set any image as desktop wallpaper. Batch Rename: Rename images in bulk using templates. Resize Images: Resize with optimized or custom resampling methods, including multi-step resizing. Thumbnail Sizes: Choose from thumbnail sizes between 32–256 pixels. Format Support: Compatible with over 100 image formats. FocusOn Image Viewer 1.32 changelog: Added Ghostscript(AI, PDF) DPI option Fixed transparency issue when saving PDF document as image Other improvements and bug fixes Download: FocusOn Image Viewer 64-bit | Portable 64-bit | ~7.0 MB (Freeware) Download: FocusOn Image Viewer 32-bit | Portable 32-bit View: FocusOn Image Viewer Website | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
  • Recent Achievements

    • First Post
      Johnny Mrkvička earned a badge
      First Post
    • Week One Done
      viraltui earned a badge
      Week One Done
    • One Month Later
      serfegyed earned a badge
      One Month Later
    • Dedicated
      firey earned a badge
      Dedicated
    • Dedicated
      fettermanj earned a badge
      Dedicated
  • Popular Contributors

    1. 1
      +primortal
      655
    2. 2
      ATLien_0
      224
    3. 3
      Michael Scrip
      224
    4. 4
      Xenon
      147
    5. 5
      +FloatingFatMan
      144
  • Tell a friend

    Love Neowin? Tell a friend!