What happened to the Messenger Plus! forums on msghelp.net?
Shoutbox » MsgHelp Archive » Skype & Technology » Tech Talk » Need VB help(Visual Basic)

Pages: (5): « First « 1 2 [ 3 ] 4 5 » Last »
Need VB help(Visual Basic)
Author: Message:
spokes
Full Member
***

Avatar
I <3 Rollerblading

Posts: 423
Reputation: 10
34 / Male / Flag
Joined: May 2004
RE: Need VB help(Visual Basic)
quote:
Originally posted by CookieRevised
    code:Private Sub Form_Load()
      Left = (Screen.Width - Width) \ 2
      Top = (Screen.Height - Height) \ 2
    End Sub

1) Why do you use the properties like "Left", "Width" and not "Form.Left", "Form.Width", etc?
2) Why do you use "\" and not "/"?

Why don't you use / ? :$


[Image: sig15ws.png]
08-22-2005 11:13 AM
Profile E-Mail PM Web Find Quote Report
CookieRevised
Elite Member
*****

Avatar

Posts: 15517
Reputation: 173
– / Male / Flag
Joined: Jul 2003
Status: Away
RE: Need VB help(Visual Basic)
Visual basic knows 2 different divisions.
One is for integers, one is for floating points.

"/" is the floating point devision. If you use that, then all variables used in the expression are first converted to floating points, then they are devided and the result will be again a floating point.

"\" is the integer devision sign. Before the expression is calculated, all the variables will be rounded down to the nearest integer (Byte, Integer, or Long) first. The result will again be an integer (and thus rounded down also).

eg:
5% / 2% = 5! / 2! = 2.5!
5! \ 2% = 5% \ 2% = 2%
89 \ 9 = 9 (and not 10; aka it is rounded down to the nearest integer, the .5 rule doesn't apply here as fractions can't exist in integers)

"%" is the marker for an 'integer'-type, "!" for a 'single'-type (aka small floating point number)

The integer devision is extremely faster than the floating point devision.

You can find this also under the topic "Arithmetic Operators" in your VB help files.

Too know exactly what integers, singles, longs, etc are look at the "Data Type Summary" topic in the help files.

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

Knowing the above, doesn't completely answer the question though.

The .Left, .Right, .Width, etc. properties of a form are always expressed in Twips*. Twips are always whole numbers, so you can't have something like 654.31 twips (unlike inches or centimeters which can be fractions)... Thus when you calculate the middle of the screen by deviding by 2, the solution must always be rounded to the nearest full unit anyways. So you better use integer devision for faster calculation (unless you want to use the .5 rule).

Left = (Screen.Width - Width) / 2
could have been used also of course. In that way VB will do actually the same, but the calculation would have been taken longer because VB needed to convert all the variables to floating points first and then calculate with floating point to end with dismissing the fraction in the end anyways.

;)


* a twip is a screen-independent, absolute unit of measurement. A twip is a unit of length equal to 1/20 of a printer's point, and a printer's point is 1/72 of an inch. There are approximately 1440 twips to a logical inch or 567 twips to a logical centimeter (the length of a screen item measuring one inch or one centimeter when printed). Other means of measurement include characters (not to be confused with the term "a character"), pixels (the smallest possible unit) and himetrics (unless you do very advanced stuff in VB you would never encounter or use himetrics though).

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

All this info is also available in the VB help files ;)

This post was edited on 08-22-2005 at 12:09 PM by CookieRevised.
.-= A 'frrrrrrrituurrr' for Wacky =-.
08-22-2005 11:44 AM
Profile PM Find Quote Report
dylan!
Senior Member
****

Avatar
l33t p4int3r

Posts: 665
Reputation: 30
– / Male / Flag
Joined: Jan 2005
O.P. RE: Need VB help(Visual Basic)
ok ive study lots in the last couple of days and if learnt wuite a bit:P and i think ive read over 50 pages of tutorials on it on the internet:P and i was just wondering one small and simple question
ok I want to create a folder and file on the click of a button but i was wondering what i would put to create it?????
e.g
Create "C:\Program Files\Program\Info.txt"
but i know create isnt a valid command and i was wondering what i could put to create it
08-25-2005 12:49 AM
Profile E-Mail PM Find Quote Report
matty
Scripting Guru
*****


Posts: 8336
Reputation: 109
39 / Male / Flag
Joined: Dec 2002
Status: Away
RE: Need VB help(Visual Basic)
I sure hope you understand this
Checks if a folder exists on the drive
code:
Private Sub Form_Load()
    DoesFolderExist "C:\My Test Folder", True
End Sub

Public Function
DoesFolderExist(strPath As String, Optional blnCreateFolder As Boolean = False) As Boolean
On Error GoTo e:
    ChDir strPath
    DoesFolderExist = True
    Exit Function

e:
    If blnCreateFolder = True Then
        MkDir strPath
    End If
    DoesFolderExist = False
End Function

Checks if a file exists and it not creates it
code:
Private Sub Form_Load()
    DoesFileExist "C:\My Test Folder\test.txt", True
End Sub

Public Function
DoesFileExist(strFile As String, Optional blnCreateFile As Boolean = False) As Boolean
On Error GoTo
e:
    FileLen (strFile)
    DoesFileExist = True
    Exit Function

e:
    If blnCreateFile = True Then
        Open
strFile For Append As #1
        Close #1
    End If
    DoesFileExist = False
End Function


This post was edited on 08-25-2005 at 01:14 AM by matty.
08-25-2005 01:07 AM
Profile E-Mail PM Find Quote Report
CookieRevised
Elite Member
*****

Avatar

Posts: 15517
Reputation: 173
– / Male / Flag
Joined: Jul 2003
Status: Away
RE: Need VB help(Visual Basic)
:$ I feel bad about this.... but.... Matty, use the Dir() function to check if a folder or file exists so you don't need to use error checking* or changing your application path ;) :$

* it still isn't totally 100% fail proof of course, but you know what I mean ;)

code:
Public Function DoesFolderExist(strPath As String, Optional blnCreateFolder As Boolean = False) As Boolean
    Dim AnyFolder As Long
    AnyFolder = vbDirectory Or vbReadOnly Or vbHidden Or vbSystem Or vbArchive Or vbNormal
 
    If Dir(strPath, AnyFolder) <> "" Then
        DoesFolderExist = True
    Else
        If blnCreateFolder Then
            MkDir strPath
        End If
        DoesFolderExist = False
    End If
End Function


Public Function DoesFileExist(strFile As String, Optional blnCreateFile As Boolean = False) As Boolean
    Dim AnyFile As Long
    AnyFile = vbReadOnly Or vbHidden Or vbSystem Or vbArchive Or vbNormal
 
    If Dir(strFile, AnyFile) <> "" Then
        DoesFileExist = True
    Else
        If blnCreateFile Then
            Open strFile For Output As #1
            Close #1
        End If
        DoesFileExist = False
    End If
End Function


IMPORTANT: I suddenly remembered why I never used Dir() for this myself (but the windows API's instead): There is a small, but important, 'twitch' in the Dir() function and the vbDirectory attribute usage (this goes for many programming languages btw, not only VB). Hence, the above "DoesFolderExist" procedure isn't 100% "bug" free and the ones below should be used instead. Sorry for this late, but important, addition...

Because of the nature of the attributes of files and directories in Windows, there can be false positives returned when searching for a directory. eg: Dir() will also return a file name (if the name matches of course), even if the vbDirectory attribute is given as a mandatory attribute to have.

To overcome this, you can make sure that the given path ends with "\". If the path exists the Dir() function will return the special file "." (meaning current directory), if not it will return an empty string "", and no false positive will be given anymore.

BUT! by adding the "\" at the end, you actually force Dir() to use the given variable as 'a path name'. If there is that file again with the same name as the last subdir in that path you wanna check, it will not produce a false positive anymore, but a runtime error 52. This is because there was a name conflict when looking up the path (which thus actually wasn't a valid path for Windows)...

Thus, to compensate for this, we need to understand how files on a computer work and how to use "special" filenames. To make it short (you can read detailed stuff about this on the net), you can/should use the special filename "NUL".

With this, we can check for the NUL-file/path. An added bonus to this is that we don't need to specify the other attributes anymore (except for vbDirectory of course) and that invalid characters (like , ; : / etc.) don't trigger an error either!

We still need to check for false positives though, but the name conflicts will not occur anymore...

code:
' "Byval" because we are going to change the variable,
' and we don't want the original passing variable to
' change with it...

Function DoesFolderExist(ByVal strPath As String) As Boolean
      ' Set the default returning value
      DoesFolderExist = False
   
      ' Make sure we start with a clean file/path name
      If Right$(strPath, 1) = "\" Then strPath = Left$(strPath, Len(strPath) - 1)
   
      ' Check for a matching name
      If Dir(strPath & "\nul", vbDirectory) = "nul" Then
          ' Compensate for false positives (matching file names)
          If GetAttr(strPath) And vbDirectory Then
              ' We truely have an existing directory at our hand
              DoesFolderExist = True
          End If
      End If   
End Function
Second important note: I left out the creation of the directory because it also isn't as strait forward as simply stating MkDir strPath. For starters, each dir above the last subdir must exist before you can create that last subdit. eg: if "C:\MyDir" doesn't exist, you can not do MkDir "C:\MyDir\SubDir".


Last note: simply use the Windows API, life is much easier (and in this case faster and shorter) with that...


PS: The "DoesFileExist" procedure doesn't suffer from all this because, vice versa, files don't have the vbDirectory attribute in the first place and thus a directory will never be returned, even if the name matches a directory! But again, creating a file isn't as strait forward as it is originally stated; there are lots of errors which could occur. And therefore, the DoesFileExist() function can be reduced to (following the same NUL-usage to compensate for bad characters):
code:
Public Function DoesFileExist(strFile As String) As Boolean
  If Dir(strFile & "\nul") = "nul" Then
    DoesFileExist = (GetAttr(strFile) And (vbDirectory Or vbVolume)) = 0
  End If
End Function


Personal note: the usage of the NUL-file/path in these ways is something I nowhere found on the net, it isn't even mentionned on so called prof, advanced or hardcore VB sites. Instead all you find are half-arsed (excuse for the wording) copy/pasted sources. I wonder how many actually know about this :/



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

Anyways, to come back to the subject.... :P


quote:
Originally posted by dylan!
ok ive study lots in the last couple of days and if learnt wuite a bit:P and i think ive read over 50 pages of tutorials on it on the internet:P and i was just wondering one small and simple question
ok I want to create a folder and file on the click of a button but i was wondering what i would put to create it?????
e.g
Create "C:\Program Files\Program\Info.txt"
but i know create isnt a valid command and i was wondering what i could put to create it

it isn't so simply though.... There are lots of things to do and to keep in mind when doing something like that.

* What do you want to do if the file already exists? Overwrite it? Append to it?
* What do you want to do when the directory (or subdirectories) don't exist? Create them?
* What if the file and/or directories do exist, but can't be overwritten?
* What kind of data are you going to write to the file? Binary? Text?
* Do you want the file to be locked for writing by another process while you are writing to it?
* Do you want the file to be locked for reading by another process while you are writing to it?
* etc...

But basically, disregarding all those questions it goes like:

code:
Open "C:\Program Files\Program\Info.txt" For Output As #1
    Print #1, "some line"
    Print #1, "some other line"
    Print #1, "more lines"
Close #1
This creates/overwrites the file, without locking it, and write ascii text to it, while assuming the directory exists and is accessible and without checking for disk quota or other errors that might occur.


As said before, use your Visual Basic Documentation which is installed when you installed Visual Basic by pressing <F1>.... Or you can lookup that same documentation online by going to the MSDN Library:
http://msdn.microsoft.com/library/default.asp?url...html/vb6anchor.asp


eg:
The specific docs for the used statements and commands in the above example:
* Open statement
* Print # statement
* Close statement


Learn to use the Visual Basic documentation and/or MSDN Library ;)

This post was edited on 09-14-2005 at 03:43 AM by CookieRevised.
.-= A 'frrrrrrrituurrr' for Wacky =-.
08-25-2005 03:49 AM
Profile PM Find Quote Report
dylan!
Senior Member
****

Avatar
l33t p4int3r

Posts: 665
Reputation: 30
– / Male / Flag
Joined: Jan 2005
O.P. RE: Need VB help(Visual Basic)
thanks cookie again;):P but when i click F1 it says it couldnt find and mds library or something8-)
08-25-2005 10:50 PM
Profile E-Mail PM Find Quote Report
CookieRevised
Elite Member
*****

Avatar

Posts: 15517
Reputation: 173
– / Male / Flag
Joined: Jul 2003
Status: Away
RE: Need VB help(Visual Basic)
quote:
Originally posted by dylan!
thanks cookie again;):P but when i click F1 it says it couldnt find and mds library or something8-)
You don't happen to have an illegal VB version don't you? Anyways you can also use the msdn library for vb on the net...

more specifically The Visual Basic Document: Programmers Reference. There you'll find every command, statement, whatever you can use with full detailed explanations. eg: see my previous post and the links to the "Open", "Print #" and "Close" statement.



This post was edited on 08-26-2005 at 12:23 AM by CookieRevised.
.-= A 'frrrrrrrituurrr' for Wacky =-.
08-25-2005 11:53 PM
Profile PM Find Quote Report
dylan!
Senior Member
****

Avatar
l33t p4int3r

Posts: 665
Reputation: 30
– / Male / Flag
Joined: Jan 2005
O.P. RE: Need VB help(Visual Basic)
no i wouldnt be using an illegal version8-)....anyways ive done a couple little things already...calculators and stuff but im stuck...i need to take text from a .txt file and put it into a msgbox

code:
Private Sub Command2_Click()
Open "C:\Program Files\Multi-app\password.txt" For Output As #1
Pass = "C:\Program Files\Multi-app\password.txt"
MsgBox (#1 & " is your Password.")
Close #1
End Sub

BUT....theres an error on the "MsgBox (#1 & " is your Password.")" line with the #1 and i was wondering what i could do to fix that8-)
09-11-2005 08:18 AM
Profile E-Mail PM Find Quote Report
spokes
Full Member
***

Avatar
I <3 Rollerblading

Posts: 423
Reputation: 10
34 / Male / Flag
Joined: May 2004
RE: Need VB help(Visual Basic)
code:
Private Sub Command2_Click()
Open "C:\Program Files\Multi-app\password.txt" For Input As #1
line input #1, pass
MsgBox (pass & " is your Password.")
Close #1
End Sub

[Image: sig15ws.png]
09-11-2005 08:32 AM
Profile E-Mail PM Web Find Quote Report
dylan!
Senior Member
****

Avatar
l33t p4int3r

Posts: 665
Reputation: 30
– / Male / Flag
Joined: Jan 2005
O.P. RE: Need VB help(Visual Basic)
still doesnt work heres my complete code8-)

code:
Dim intMsg, Message As String
Private Sub Command2_Click()
Open "C:\Program Files\Multi-app\password.txt" For Input As #1
Line Input #1, Pass
MsgBox (Pass & " is your Password.")
Close #1
End Sub
Private Sub Command3_Click()
Open "C:\Program Files\Multi-app\password.txt" For Append As #1
intMsg = MsgBox("Password Rememberer opened.")
Message = InputBox("Enter Password")
Print #1, intMsg; Message

Close #1
End Sub

Private Sub Command1_Click()
Dim Pass As Integer
Open App.Path & "C:\Program Files\Multi-app\password.txt" For Input As #1
Pass = InputBox("Enter Password.")
MsgBox (Pass & " remembered.")

End Sub

Public Function DoesFolderExist(strPath As String, Optional blnCreateFolder As Boolean = False) As Boolean
    Dim AnyFolder As Long
    AnyFolder = vbDirectory Or vbReadOnly Or vbHidden Or vbSystem Or vbArchive Or vbNormal
 
    If Dir(strPath, AnyFolder) <> "" Then
        DoesFolderExist = True
    Else
        If blnCreateFolder Then
            MkDir strPath
        End If
        DoesFolderExist = False
    End If
End Function


Public Function DoesFileExist(strFile As String, Optional blnCreateFile As Boolean = False) As Boolean
    Dim AnyFile As Long
    AnyFile = vbReadOnly Or vbHidden Or vbSystem Or vbArchive Or vbNormal
 
    If Dir(strFile, AnyFile) <> "" Then
        DoesFileExist = True
    Else
        If blnCreateFile Then
            Open strFile For Output As #1
            Close #1
        End If
        DoesFileExist = False
    End If
End Function

Private Sub Form_QueryUnload(Cancel As Integer, UnloadMode As Integer)
  If MsgBox("Are you sure you want to shut down?", vbYesNoCancel) <> vbYes Then
    Cancel = True
  End If
End Sub



Private Sub mnuHelp_Click(Index As Integer)
MsgBox "Please email me at lucky_number_15s@hotmail.com for any help or SUGGESTIONS!"
End Sub
09-11-2005 09:03 AM
Profile E-Mail PM Find Quote Report
Pages: (5): « First « 1 2 [ 3 ] 4 5 » Last »
« Next Oldest Return to Top Next Newest »


Threaded Mode | Linear Mode
View a Printable Version
Send this Thread to a Friend
Subscribe | Add to Favorites
Rate This Thread:

Forum Jump:

Forum Rules:
You cannot post new threads
You cannot post replies
You cannot post attachments
You can edit your posts
HTML is Off
myCode is On
Smilies are On
[img] Code is On