[RESOLVED] Can I save the contents in a listbox using CommonDialog?
I'm trying to figure out how to save the contents in a listbox:
1
2
3
4
5
using the CommonDialog so the user can create a filename and click Save.
Re: Can I save the contents in a listbox using CommonDialog?
I figured it out
VB Code:
Private Sub Command2_Click()
On Error Resume Next
With CommonDialog1 'open a with statement as there is a lot of code
.DialogTitle = "Save" 'sets the dialog title
.InitDir = "C:\" 'sets the initial directory
.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*" 'sets the file
'types
.ShowSave 'show the dialog
End With
Open CommonDialog1.FileName For Output As #1
For X = 0 To List2.ListCount
Print #1, List2.List(X)
Next
Close #1
End Sub
Re: [RESOLVED] Can I save the contents in a listbox using CommonDialog?
The list indexes in the listbox start at 0 and go to .listcount-1. Just to keep in mind since you might notice that you have an extra empty line at the end of your file :)
Re: [RESOLVED] Can I save the contents in a listbox using CommonDialog?
...also,
1. Don't use hard-coded file number. Use FreeFile function.
2. Trap when user presses Cancel. (Set, CommonDialog1.CancelError = True , and trap cdlCancel error in error handler. :)
VB Code:
Private Sub Command1_Click()
On Error Goto ErrChkr
Dim F As Integer
Dim i As Integer
With CommonDialog1
.FileName = ""
.DefaultExt = ".txt"
.Filter = "Text file|*.txt"
.Flags = cdlOFNOverwritePrompt 'Overwrite prompt
.CancelError = True
.ShowSave
F = Freefile
Open .FileName For Output As #F
For i = 0 To List1.ListCount - 1
'Save each listitem
Print #F, List1.List(i)
Next i
Close #F
End With
Exit Sub
ErrChkr:
If Err.Number = cdlCancel Then
Msgbox Err.Description
' do whatever else you want to do if cancel was clicked
End If
End Sub
Re: [RESOLVED] Can I save the contents in a listbox using CommonDialog?
Quote:
Originally Posted by iPrank
...also,
1. Don't use hard-coded file number. Use FreeFile function.
2. Trap when user presses Cancel. (Set, CommonDialog1.CancelError = True , and trap cdlCancel error in error handler. :)
VB Code:
Private Sub Command1_Click()
On Error Goto ErrChkr
Dim F As Integer
Dim i As Integer
With CommonDialog1
.FileName = ""
.DefaultExt = ".txt"
.Filter = "Text file|*.txt"
.Flags = cdlOFNOverwritePrompt 'Overwrite prompt
.CancelError = True
.ShowSave
F = Freefile
Open .FileName For Output As #F
For i = 0 To List1.ListCount - 1
'Save each listitem
Write #F, List1.List(i)
Next i
Close #F
End With
Exit Sub
ErrChkr:
If Err.Number = cdlCancel Then
Msgbox Err.Description
' do whatever else you want to do if cancel was clicked
End If
End Sub
If memory serves me right, Write() adds quotation marks ("") around the data and Print() doesn't... Could be wrong though...
Re: [RESOLVED] Can I save the contents in a listbox using CommonDialog?
Oops ! :p
You are right. :thumb:
Code edited.