Wednesday, March 26, 2014

How to adjust automatically the width of the columns?(VBA-Excel)

This might be the easiest command you have ever seen in VBA. ;)

Sub columns_adjust()

Columns.Autofit

End Sub


Monday, March 24, 2014

How to find a maximum of a range (VBA-Excel)

Sub maximum()

Range("t11").Value = Application.Max(Range("e1:e20"))

End Sub

Tuesday, March 18, 2014

How to iterate over the files in a folder (VBA-Excel)

On our example below, we iterate over all text files (*.txt) inside the folder called "myfolder", please change the path according your folder and if you want to see all the files instead of just the files with a specific extension write just: "*" instead of "*.txt"

Sub over_files()

Dim file As String
Dim folderpath As String
Dim filename As String
Dim Count_files As Integer

''''''Data'''''''''''''''''''''
folderpath = "C:\Users\Guest\Desktop\myfolder\*.txt"
'''''''''''''''''''''''''''''''''''''

   file = Dir(folderpath)
  
Count_files = 0

While (file <> "")

    If Len(file) > 0 Then
    filename = Left(file, Len(file) - 4)
    Count_files = Count_files + 1
    End If
  
   ' your code here

     file = Dir

Wend

End Sub



Monday, March 17, 2014

How to know the running time of a macro (VBA-Excel)?

Just use the following code and the running time of your macro will be printed, in seconds, on the immediate window:

Sub macro1()

Dim starttime, endtime As Double

starttime = Now

' your code here

endtime = Now
Debug.Print "Macro ran successfully in " & DateDiff("s", starttime, endtime) & " seconds"

End Sub

Tuesday, March 11, 2014

How to import or remove a .frm file into your VBA project?

Sub to_import()
Application.VBE.ActiveVBProject.VBComponents.Import "c:\temp\myform.frm"
End Sub

Sub to_remove()
Application.VBE.ActiveVBProject.VBComponents.Remove Application.VBE.ActiveVBProject.VBComponents("Userform1")
End sub

P.S: Before running please allow the macro to change its own script, on "Macro Security".
Check the following option: "Trust access to the VBA Project object model".


Friday, March 7, 2014

Macro is executed just during seven days (VBA-Excel)

Sub Your_macro()

If DateSerial(Year(Date), Month(Date), Day(Date)) - DateSerial(2014, 3, 7) < 7 Then

'your code here

End If

End sub

Wednesday, March 5, 2014

How to delete a file with VBA?

Sub delete_specific_file()

Kill "C:\folder\filename.xls"

End Sub