VBA Excel User Form Output to Txt File - vba

I am trying to create a user form that takes user input and prints to a text file. I know the VBA scripting functions to print, store strings etc. BUT I'm new to userforms. How do you limit input and output to a text file? Add to that same file?
INPUT AND OUTPUT:
I would need to have this variety of
KEY FEATURES:
Limited Entry: XXXX means only enter 4 characters (The notepad file can only be certain characters long
Multiple Entries: After a set of records is entered to the text file, their values are stored and another input is allowed. Also the new entries have to be written to the same file on the next line
Space if left blank: If XXXX is left blank then four " " should be printed instead.
If you have part or all of these answers I'd like to hear from you!
---------------------------Edited with Adding Code-----------------------------
Private Sub Userform_Initialize()
'Fill Eggs
With Eggs
.AddItem "Eggs"
End With
End Sub
Private Sub CreateList_Click()
Dim myFile As String, myString As String
myFile = "C:\Reformatted.txt"
Open myFile For Output As #1
Dim fourChars As String * 4
fourChars = Milk.Value
myString = Eggs.Value + Milk.Value + Bread.Value
Print #1, myString
Close #1
Shell "C:\Windows\Notepad.exe C:\Reformatted.txt", 1
End Sub
So the above code launches this screen:

TextBox have MaxLength property. Default is set to 0 which does not limit character entry.
To limit the entry into a certain number, just change the value of this property to that number.
Now for replacing the XXXX with blank(if none or less than 4 is entered), take on SO advise in the comments.
Dim fourChars As String * 4
fourChars = TextBox1.Value
MsgBox Len(fourChars) ' will always return 4

Related

Ammend code to include drop down selection instead of type-in prompt

I have the following code which prompts the user which open file/window to switch to. I am using this to get around the fact the name of my dependent data file is changing on a daily basis. The following code works. However, instead of asking in the prompt box to type the name of the file to switch to, I would like for it to recognize the open files and give me a drop down or some sort of selection to choose from to just select the file I want to switch to.
Anybody know how to do that?
Sub switch()
Dim i As Integer
Dim n As Integer
Dim s As String
Dim t As Variant
n = Windows.Count
s = "Pick From:"
For i = 1 To n
s = s & Chr(10) & Windows(i).Caption
Next
t = Application.InputBox(prompt:=s, Type:=2)
If t = False Then
Exit Sub
End If
Windows(t).Activate
End Sub

how to set the decimal separator for printing to file different from the system setting

Using VBA in Excel 2010 I want to print the contents of a cell in a worksheet which is a decimal number to a file. I am using the ´Print #´ statement for this. I am working in an environment where the comma ´,´ is the system wide decimal separator. For the printout I want the point ´.´ to be the decimal separator.
The following code does NOT work:
Public Sub printDecimal()
Application.UseSystemSeparators = False
Application.DecimalSeparator = "."
Open "testfile.txt" For Output As #1
Print #1, ActiveSheet.Range("A1").Value
Close #1
Application.UseSystemSeparators = True
End Sub
The documentation for the Print # statement says:
All data written to the file using Print # is internationally aware;
that is, the data is properly formatted using the appropriate decimal
separator.
When I change the system wide settings in Windows 7 Enterprise Control Panel, I get the desired output, but this is not what I want.
Since you are using a macro, you can take direct control of the material being output to the text file:
Public Sub printDecimal()
Dim st As String
Close #1
Open "C:\TestFolder\testfile.txt" For Output As #1
st = Range("A1").Text
st = Replace(st, ",", ".")
Print #1, st
Close #1
End Sub
Using the .Text property allows you to get the cell's value WYSIWYG. The rest is just string manipulation.
EDIT#1:
The reason the posted code does not work is that applying Application.DecimalSeparator is akin to applying formats......the underlying value does not change. Run this to see the difference:
Sub demo()
Dim st As String, st2 As String
Application.UseSystemSeparators = False
Application.DecimalSeparator = "|"
Close #1
Open "C:\TestFolder\testfile2.txt" For Output As #1
Print #1, ActiveSheet.Range("A1").Value & vbCrLf & ActiveSheet.Range("A1").Text
Close #1
Application.UseSystemSeparators = True
End Sub

dynamically select sheet from the inputprompt and print to a file

i have 3 sheets in my workbook namely sheet1 ,sheet3 and sheet2 when i enter a values from in the inputpromt say (eg:1,2 ) i split it and store it in an array it must dynamically select the sheet1 and sheet2 and print values to a file.
i have done a pseudo below can any one
Sub example()
Dim Ran As Range
Dim cnt as String
Open "D:\temp\test.txt" For Output As #1
Dim myarray() As String
Dim holder As String
dim ab as Strig
ab="this is sample data"
holder = InputBox("Enter your choice eg:1,2")
myarray = Split(holder, ",")
Dim name, country,birth As String
For i = 1 To UBound(myarray)
If i = 1 Or i = 2 Then
name = Sheets(i).Range("Z12").Value
country= Sheets(i).Range("PQ26").Value
birth = Sheets(i).Range("ab24").Value
ab=ab & name & country & birth
Print #1, ab
End If
Next i
end Sub
****in the inputbox if i give value as 1,2 then it must select values from sheet 1 and sheet2****
I am guessing you that you are trying to understand InputBox and how to split a string such as “1, 2” and process the separate values as sheet numbers.
Sheet numbers mean nothing to the user so I do not believe this is a good approach. You need to offer the user a list of worksheet tabs from which they can select.
There is InputBox and Application.InputBox. These are different and I do not like either. They come from the earliest versions of VB and were probably originally a direct match to MS-DOS’s console input. With one exception, there are much better approaches. The one exception is the ability to input a range with Application.InputBox for which I do not know a convenient alternative.
In the code below I use InputBox. You may think I have overdone the validation but what if the user enters “A”? Your code would assume “A” was a sheet number but Excel would assume it was a worksheet name and stop execution with a subscript error. You must check for any error that will cause your code to stop with a run-time error.
Instead of either InputBox you should use a User Form. There are on-line tutorials to get you started. With a User Form you have several choices including:
A List box, with multiple selection enabled, containing the names of every permitted worksheet.
A column of radio buttons, one per permitted worksheet. These would be unlinked so the user could select several.
A command button for each permitted worksheet which the user could click in turn.
All of these choices are much user-friendlier than InputBox.
Step through the code below with F8 and study what it does. Come back with questions if necessary but the more you can understand on your own the faster you will develop.
Option Explicit
' Please indent your macros consistently. This makes them much easier ri read
Sub example()
Dim Ran As Range
Dim cnt As String
Dim myarray() As String
Dim ab As String
' Variables I have added or which are replacements for yours.
Dim Answer As String
Dim AllValuesGood As Boolean
Dim InxMA As Long
Dim InxSht As Long
Dim Question As String
' I like to keep all my Dim statements together at the top.
' This makes them easier to find.
Dim name, country, birth As String
' I have output to the Immediate window which is simpler when
' experimenting.
'Open "D:\temp\test.txt" For Output As #1
Question = "Enter your choice eg: ""1"" or ""1,2"""
' You omitted the code to check the Answer
Do While True
Answer = InputBox(Question, "Experiment with Input box")
' Have a string but user could have typed anything
If Answer = "" Then
' Cannot tell if user has clicked Cancel or if user clicked Return
' before entering value. Have to assume Cancel
Debug.Print "User clicked Cancel"
Exit Sub
Else
AllValuesGood = True ' Assume good answer until find otherwise
myarray = Split(Answer, ",")
For InxMA = 0 To UBound(myarray)
If IsNumeric(myarray(InxMA)) Then
InxSht = Val(myarray(InxMA))
If InxSht < 1 Or InxSht > 2 Then
' Sheet number outside permitted range
AllValuesGood = False
Exit For
End If
Else
' Non-numeric sheet number
AllValuesGood = False
'Debug.Assert False
Exit For
End If
Next
End If
If AllValuesGood Then
' Have good answer. Exit Do-Loop to print sheets
Exit Do
Else
' An invalid sheet number has been found
Question = "Click cancel to exit or enter ""1"" or ""2"" or ""1, 2"""
' Loop to repeat Input
End If
Loop ' Until have good answer
' If get here Answer is a list of good sheet number
For InxMA = 0 To UBound(myarray)
InxSht = Val(myarray(InxMA))
' I have not created sample worksheets with data in Z12, PQ26 and ab24
' but this shows the code you need
'With Worksheets(InxSht)
' name = .Range("Z12").Value
' country = .Range("PQ26").Value
' birth = .Range("ab24").Value
'Next
name = "Name" & InxSht
country = "Country" & InxSht
birth = "Birth" & InxSht
' Have to initialise ab here because need new value per sheet
ab = "this is sample data"
ab = ab & name & country & birth
Debug.Print ab
' The value of ab will be messy because you have no spaces between words.
'Print #1, ab
Next InxMA
End Sub

open outlook mail in customized form

I have created a small application in Excel-VBA which takes inputs from a user and the application sends and email to me the inputs in an encrypted form.
Now, I have a macro in outlook-vba which takes care of decryption and saves data in required format, so that's not a problem. What I need is I want to open that specific mail from the user in a customized format so that without running that script I could see the data.
E.g. The data comes in like this
1~Saurav Gupta~100^2~Sachin Rana~200^
Now I want it to be shown as in a tabular format in a form, say
S.No Name Marks
1 Saurav Gupta 100
2 Sachin Rana 200
Any idea how can I achieve that?
Thanks and regards
Saurav.
Use the builtin Split function to separate the lines and the fields in the data:
Option Explicit
Sub SplitTest()
Dim sInput As String
Dim sLines() As String
Dim sFields() As String
Dim iLine As Integer
sInput = "1~Saurav Gupta~100^2~Sachin Rana~200^"
'***** Split sInput into lines
sLines = Split(sInput, "^")
'***** Do something with the lines
For iLine = 0 To UBound(sLines) - 1
Debug.Print sLines(iLine)
'***** Split each line into fields
sFields = Split(sLines(iLine), "~")
'***** Do something with the fields
Debug.Print "#1. " & sFields(0) & ", #2. " & sFields(1) & ", #3. " & sFields(2)
Next iLine
End Sub

VBA duplicate PDF file

I really need help. I need a VBA function to make copies of a single PDF file. For example a file with the reference/name 1, I would need an amount x of copies lets say 1 to 10. In order to avoid coping and paste 9 times and renaming them manually I am sure there must be a function to do this job. I am very basic with VBA so any help would be much appreciated.
Many Thanks
First you will need to add a reference to Microsoft Scripting Runtime in the VBA editor. Then the following will work...
Public Sub Test()
CopyFile "C:\Users\randrews\Desktop\1.gif", "C:\Users\randrews\Desktop", 10
End Sub
Public Sub CopyFile(OriginalPath As String, DestinationFolderPath, Copies As Integer)
Dim fs As New FileSystemObject
For i = 1 To Copies
OrigName = fs.GetFileName(OriginalPath) 'file name with extention e.g. 1.gif
OrigNumber = CInt(Left(OrigName, Len(OrigName) - 4)) 'file name converted to a number - this will crash if the file name contains any non numeric chars
DestName = OrigNumber + i & "." & fs.GetExtensionName(OriginalPath) 'new file name = original number + i + the file extension
fs.CopyFile OriginalPath, DestinationFolderPath & "\" & DestName
Next i
End Sub