[VBA] half recorded, half declared

Obviously, something I haven’t mentioned yet: there is a possibility to record macros in Excel.
It might be fast and useful way to automate some basic moves in our workbooks, but it is not as much flexible as declaring variables, loop and arrays.
For some projects we can use combination of both ways to create really good looking code suitable for our daily process.

Today I am going to present a short template I have created few days ago. A really similar solution I am using right now in the office.

Let’s create quickly 2-3 reports with .txt extansion

and save it as Report_20181210.txt
The main goal is to create a simple macro, which let final user to choose the path and importing the report into the selected sheet.

At first we will record the steps, that we are doing while we import report into excel.
cLet’s got to the top tabs, select Developer and then click on: Record Macro.

Now, let’s go to data – import txt file and follow the steps suggested by Excel.

After we need to switch off the recording.
Now take a look at what has been saved by Excel in VBA Editor. On the list of Project Exloplorer, there will be a new module with a code like this one :

recording

Looks nice but need to by a little modified.

Lets write a following Procedure:

Sub ImportReport()

Dim Answer As VbMsgBoxResult
Dim TxtPath As Office.FileDialog
Dim TxtFile As String

Set TxtPath = Application.FileDialog(msoFileDialogFilePicker)

With TxtPath
.AllowMultiSelect = False
.Title = "Please choose a folder to insert a Report file:"
.Filters.Clear
.Filters.Add "All", "*.*"

If .Show = True Then
TxtFile = Dir(.SelectedItems(1))
Sheets.Add.Name = TxtFile

End If
End With

Answer = MsgBox("Do you want to import: " & TxtFile &"?" , _
vbYesNo, "Importing")

If Answer = vbYes Then
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;" & TxtPath.SelectedItems(1), Destination:=Range( _
"$A$1"))
.Name = TxtFile
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 1252
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = False
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
ElseIf Answer = vbNo Then
MsgBox "Choose file again"
End If

End Sub

At the end let’s clik on Debug –> Complie VBA Project, if everything’s fine go to RunSub (F5)

[VBA] autofilter & shell function

Autofilter is a method to present data in smaller circle of the whole database. Let’s say we have full table of various product with prices and we would like to show in next sheet the result for all positions contains chosen name or price of the product. We can make an example with our table Products, already exported to Excel . From the table i would like to create autofilter for Korn album in Rock sheet and Hip-hop albums cheaper then 35 PLN.

korn.jpg

Cells.Select
Cells.EntireColumn.AutoFit
Columns("A:A").Select
Selection.AutoFilter
Rows("1:1").Select
Selection.AutoFilter
Selection.AutoFilter
ActiveSheet.Range("$A$1:$I$54").AutoFilter Field:=2, Criteria1:="KORN"
Range("A1:I9").Select
Selection.Copy
Sheets("ROCK").Select
ActiveSheet.Paste
Cells.Select
Cells.EntireColumn.AutoFit

ActiveSheet.Range("$A$1:$I$54").AutoFilter Field:=2, Criteria1:= _
"=DonGuralEsko", Operator:=xlOr, Criteria2:="=Pezet"
ActiveSheet.Range("$A$1:$I$54").AutoFilter Field:=9, Criteria1:="<35", _
Operator:=xlAnd
Range("B1:I47").Select
Selection.Copy
Sheets("HH").Select
Range("A1").Select
ActiveSheet.Paste
Cells.Select
Cells.EntireColumn.AutoFit
Range("A1").Select

Shell: you have already seen examples to open or save dedicated file with various extenstion in my previous posts. But here’s another option of VBA code, which is similar do CMD command. It’s a VBA Shell function. Try this by your own:

'open up a notepad
shell1 = Shell("notepad")
'open up Ms Access
shell2 = Shell("msaccess")'Excel
shell3 = Shell("excel")
'direct path and file
shell4 = Shell("notepad C:\Users\user\Desktop\wyliczenie.txt")
shell5 = Shell("explorer.exe C:\Users\user\Desktop\wyliczenie.txt")