Monday, April 20, 2015

Hide the excel workbook while macro is running

Minimise the workbook or insert a blank sheet and activate it before starting the rest of your macro. Also:

Application.ScreenUpdating = False

will suppress screen activity. Set it back to True at the end.

Saturday, April 18, 2015

Switch statement

Syntax:
Select Case Expression
 
Case expressionlist1      
statement1      
statement2 .... .... statement1n   
Case expressionlist2      
statement1      
statement2 .... ....   
Case expressionlistn      
statement1      
statement2 .... ....  
Case Else      
elsestatement1      
elsestatement2 .... ....
End Select



Note: I had a value that i wanted to compare with list of values, when i tried to use if statement using OR or AND statement, it did not work because if statement is not comparing each value but compare only one value and turns other conditions to true. here is the ex:

if ((currentphase <> "test") OR (currentphase <>"development") OR (currentphase <> "Release and deployment") OR (currentphase <> "Warranty") then

--- here if the current phase is test, then rest all conditions will be true, that way everytime if is executing as True.

Alternate is Switch. This is useful to compare the value with list of values, if none of them matches go with else statement.

Tuesday, April 14, 2015

Formatting the cells in the excel sheet



4/14/15-----
'Formatting the copied cells
        'select sheet - Anita
       Sheets("Anita").Select

     'Select first cell, it is where you wanted to start select the area.
    Range("A25").Select

     'End(xlDown) - will take the cursor till last row where the data exist
    Range(Selection, Selection.End(xlDown)).Select
     'End(xlToRight) - will take the cursor to the last column where the data exist
    Range(Selection, Selection.End(xlToRight)).Select

    Selection.Borders(xlDiagonalDown).LineStyle = xlNone
    Selection.Borders(xlDiagonalUp).LineStyle = xlNone
     'Row height adjustment- 15
    Selection.RowHeight = 15
    With Selection.Borders(xlEdgeLeft)
        .LineStyle = xlContinuous
        .ColorIndex = 0
        .TintAndShade = 0
        .Weight = xlThin
    End With
    With Selection.Borders(xlEdgeTop)
        .LineStyle = xlContinuous
        .ColorIndex = 0
        .TintAndShade = 0
        .Weight = xlThin
    End With
    With Selection.Borders(xlEdgeBottom)
        .LineStyle = xlContinuous
        .ColorIndex = 0
        .TintAndShade = 0
        .Weight = xlThin
    End With
    With Selection.Borders(xlEdgeRight)
        .LineStyle = xlContinuous
        .ColorIndex = 0
        .TintAndShade = 0
        .Weight = xlThin
    End With
    With Selection.Borders(xlInsideVertical)
        .LineStyle = xlContinuous
        .ColorIndex = 0
        .TintAndShade = 0
        .Weight = xlThin
    End With
    With Selection.Borders(xlInsideHorizontal)
        .LineStyle = xlContinuous
        .ColorIndex = 0
        .TintAndShade = 0
        .Weight = xlThin
    End With
    Range("A25").Select
    Range(Selection, Selection.End(xlToRight)).Select
    With Selection.Interior
        .Pattern = xlSolid
        .PatternColorIndex = xlAutomatic
        .ThemeColor = xlThemeColorLight2
        .TintAndShade = 0.399975585192419
        .PatternTintAndShade = 0
    End With
    Selection.Font.Bold = True
    Range("A25").Select
    Range(Selection, Selection.End(xlDown)).Select
    Range(Selection, Selection.End(xlToRight)).Select
    With Selection
        .HorizontalAlignment = xlGeneral
        .VerticalAlignment = xlBottom
        .WrapText = True
        .Orientation = 0
        .AddIndent = False
        .IndentLevel = 0
        .ShrinkToFit = False
        .ReadingOrder = xlContext
        .MergeCells = False
    End With
    With Selection
        .HorizontalAlignment = xlGeneral
        .VerticalAlignment = xlBottom
        .WrapText = True
        .Orientation = 0
        .AddIndent = False
        .IndentLevel = 0
        .ShrinkToFit = False
        .ReadingOrder = xlContext
        .MergeCells = False
    End With

Wednesday, April 8, 2015

Copy the data in excel along with format

ActiveWorkbook.Sheets("Anita").Rows("25:" & lastrow).PasteSpecial Paste = xlValues

' PasteSpeical -- should help -- paste speical does not paste the copied content with the format.

' I dont know only this works

ActiveWorkbook.Sheets("Anita").Rows("25:" & lastrow).PasteSpecial -4163


With Worksheets("Sheet1")
    .Range("C1:C5").Copy
    .Range("D1:D5").PasteSpecial _
        Operation:=xlPasteSpecialOperationAdd
End With



' Apply filter and then copy data from one sheet to another in the same excel


Sub addsheet()
Worksheets.Add().Name = "copy1"

ActiveWorkbook.Sheets("Report_from_Clarity").Range("$A$1:$W$223").AutoFilter Field:=1, Criteria1:="PRJ0006FLX" & "*"
lastrow1 = Cells.Find("*", [A1], , , xlByRows, xlPrevious).Row
MsgBox (lastrow1)

ActiveWorkbook.Sheets("Report_from_Clarity").Rows("1:" & lastrow1).Copy ActiveWorkbook.Sheets("copy1").Rows("1:" & lastrow1)


lastrow2 = Cells.Find("*", [A1], , , xlByRows, xlPrevious).Row
MsgBox (lastrow2)

End Sub

Hide Rows and columns

 ActiveWorkbook.Sheets("Anita").Rows("16:23").Hidden = True
   
    'Selection.EntireRow.Hidden = False

Format excels and clear the old format and data


4/8/15:

objExcel.Cells(1, 1).Value = "Name"
objExcel.Cells(1, 1).Font.Bold = TRUE
objExcel.Cells(1, 1).Interior.ColorIndex = 30
objExcel.Cells(1, 1).Font.ColorIndex = 2

'List excel colors

For i = 1 to 56
    objExcel.Cells(i, 1).Value = i
    objExcel.Cells(i, 1).Interior.ColorIndex = i
Next

' Clear and ClearContent

Range("X").Cells.Clear   ' this will clear the content along with background color
Range("X").Cells.ClearContents ' clears only content


Note: Remem­ber “.Clear” will clear the every­thing from the cell right from cell data to cell for­mat­ting, bor­ders etc.

If you just want to clear the con­tent or data of the cells with­out effect­ing the for­mat and bor­der of the cell use “.ClearCon­tents

mainworkBook.Sheets(“MyFirstMacro”).Range(“C6”).ClearContents
 

Apply filter from middle of Rows and clear the filter in excel using vbscript



 Rows("3:3").Select
    Selection.AutoFilter
    ActiveSheet.Range("$A$3:$W$223").AutoFilter Field:=3, Criteria1:= _
        "Betz Jeanne M"


'to remove the filter you just mention autofilter again

 ActiveSheet.Range("$A$5:$W$223").AutoFilter



Use OR operator duirng filter(apply multiple value filter):

    ActiveSheet.Range("$A$1:$CN$25425").AutoFilter Field:=30, Criteria1:= _
        "=Application", Operator:=xlOr, Criteria2:="=Minor Enhancements"

Apply filter for a string:

ActiveSheet.Range("$A$1:$CN$25425").AutoFilter Field:=2, Criteria1:= _
        "<>*cross*", Operator:=xlAnd



Tuesday, April 7, 2015

Apply filter - and make use of the data

MasterPrjid = "PRJ0006FT9"

' Apply filter

Workbooks(clarityrpojectsfilename).Sheets("Report_from_Clarity").Range("A:W").AutoFilter Field:=15, Criteria1:=MasterPrjid & "*"

'Copy the applied filter to the next sheet name 'copy', here only the data that got filtered is getting 'copied to the sheet 'copy'

Workbooks(clarityrpojectsfilename).Sheets("Report_from_Clarity").Range("A:W").Copy  _ Workbooks(clarityrpojectsfilename).Sheets("copy").Range("A:W")

'//
' to apply more filters, you just put apply filter command twice by mentioning different field numbers


Workbooks(clarityrpojectsfilename).Sheets("Report_from_Clarity").Range("A:W").AutoFilter Field:=15, Criteria1:=MasterPrjid & "*"
Workbooks(clarityrpojectsfilename).Sheets("Report_from_Clarity").Range("A:W").AutoFilter Field:=1, Criteria1:=SubPrjid & "*"



5/8/15:

Apply filter copy unique values in a column and paste them in another column:

ActiveSheet.Range("B2:B65536").AdvancedFilter Action:=xlFilterCopy, CopyToRange:=ActiveSheet.Range("J2"), Unique:=True

Apply Filters -- use regular expression for the criteria and more

'Declaration
Function AutoFilter ( _
Field As Object, _
Criteria1 As Object, _
Operator As XlAutoFilterOperator, _
Criteria2 As Object, _
VisibleDropDown As Object _
) As Object
'Usage
Dim instance As Range
Dim Field As Object
Dim Criteria1 As Object
Dim Operator As XlAutoFilterOperator
Dim Criteria2 As Object
Dim VisibleDropDown As Object
Dim returnValue As Object

returnValue = instance.AutoFilter(Field, _
Criteria1, Operator, Criteria2, VisibleDropDown)
Field - The integer offset of the field on which you want to base the filter (from the left of the list; the leftmost field is field one).

The criteria (a string; for example, "101"). Use "=" to find blank fields, or use "<>" to find nonblank fields. If this argument is omitted, the criteria is All. If Operator is xlTop10Items, Criteria1 specifies the number of items (for example, "10").


Operator -
Can be one of the following XlAutoFilterOperator constants:
  • xlAnddefault
  • xlBottom10Items
  • xlBottom10Percent
  • xlOr
  • xlTop10Items
  • xlTop10Percent
Use xlAnd and xlOr with Criteria1 and Criteria2 to construct compound criteria.

The second criteria (a string). Used with Criteria1 and Operator to construct compound criteria.

 VisibleDropDown: True to display the AutoFilter drop-down arrow for the filtered field; False to hide the AutoFilter drop-down arrow for the filtered field. True by default.


Ex:

Workbooks("Combining excels for compliance.xlsm").Sheets("Test Lab data").Range("A:H").AutoFilter Field:=1, Criteria1:=MasterPrjid & "*", Operator:=xlFilterValues, VisibleDropDown:="True"

' Field 1 = Maser project name(here i would like to apply filter)
' Criterial = Master project id with some characters appended to it
' Not sure about other filter atrributes, even if you remove them its working..

Issue: I tried to use "*" - regular expression as mentioned in teh below code:

Ben= "Heermance"
ActiveSheet.Range("$A$1:$CN$25425").AutoFilter Field:=28, Criteria1:=Array( _
        "Goel Vikas", "*" & Ben & "*", "Radmand Payman", "Ray Michael H", "Tiku Sripriya" _
        , "Wilson Sheila K"), Operator:=xlFilterValues

But looks like regular expression does not work just like that. Mentiond the scenario in handson.

Sunday, April 5, 2015

Going to directory, finding excel files and copy the excel sheet into a new excel file

'file extension to look for
extension = "xlsx" 

  'directory to look in
'strDirectory = InputBox("Enter the Folder Path:","Folder Path") 

  strDirectory = "C:\Users\ARUN\Desktop\Excel Merger Project"

counter = 0
  'File Objects Initialization
Set objFSO = CreateObject("Scripting.FileSystemObject")

Set objFolder = objFSO.GetFolder(strDirectory)

counter = 0

set wbDst = objExcel.workbooks.open(strFileName) 'strFileName - empty file opened sometime back

For Each objFile In objFolder.Files 

  if LCase((objFSO.GetExtensionName(objFile))) = LCase(extension) then 

  counter = counter + 1

'Get the file name
  FileName = objFile.Name        

FileName = strDirectory & "\" & FileName msgbox(FileName)

set wbSrc = objExcel.workbooks.open(FileName)

wbSrc.sheets(wbSrc.Sheets(1).Name).copy wbDst.sheets(counter)

end if
Next

objWorkbook.SaveAs(strFileName) 'strFileName - is the empty excel file created sometime back

objExcel.Quit







 

Creating empty excel file

'create an empty excel file starts

strFileName = "C:\Users\ARUN\Desktop\LD.xlsx"

Set objExcel = CreateObject("Excel.Application")

objExcel.Visible = True

Set objWorkbook = objExcel.Workbooks.Add()

objWorkbook.SaveAs(strFileName)

objExcel.Quit

'created an empty excel file

' later if you want to open

objExcel.workbooks.open(strFileName)

Wednesday, April 1, 2015

Combining Excel files and making it one

'Open a file

file_Name = Application.GetOpenFilename() '-- to show the pop up window to find the file and open it
set owb=Application.Workbooks.Open(file_Name) '--capture the opened file in an object 'owb'
'MsgBox (file_Name) ' file_Name has full file path


' Count the number of Rows and Columns

Workbooks("file_Name").Sheets(1).Activate
lastrowR = Cells.Find("*", [A1], , , xlByRows, xlPrevious).Row

lastcolumnR = Cells.Find("*", [A1], , , xlByColumns, xlPrevious).Column



' Copy and Paste


Set shtToCopy = Workbooks("file_Name").Sheets(1).Range("R1:Y" & lastcolumnR)
shtToCopy.CopyWorkbooks("FCCT Project List_10-24.xlsx").Sheets(1).Range("R" & i & ":Y" & i)