Tuesday, April 9, 2019

SQL Interview Questions

Question 1: If we have two tables having 1 column each, with 4 records.













What is the number of records if you apply

JOIN
LEFT JOIN
RIGHT JOIN


Solution

Create two tables:


CREATE TABLE Test1
(
  COL1         NUMBER
);

CREATE TABLE Test2
(
  COL1         NUMBER
);


Insert records:

INSERT INTO Test1 VALUES (1);
INSERT INTO Test2 VALUES (1);


Join

select * from Test1 a JOIN Test2 b
On a.col1 = b.col1

select * from Test1 a Left JOIN Test2 b
On a.col1 = b.col1

select * from Test1 a Right JOIN Test2 b
On a.col1 = b.col1

For all the result will be below:


_______________________________________________________________________
Question 2: How to find count of duplicate rows? 
Answer:
Select rollno, count (rollno) from Student
Group by rollno
Having count (rollno)>1
Order by count (rollno) desc;
______________________________________________________________________

Question 3: How to remove duplicate rows from table?
Answer:
First Step: Selecting Duplicate rows from table
Tip: Use concept of max (rowid) of table. Click here to get concept of rowid.
Select rollno FROM Student WHERE ROWID <>
(Select max (rowid) from Student b where rollno=b.rollno);
Step 2:  Delete duplicate rows
Delete FROM Student WHERE ROWID <>
(Select max (rowid) from Student b where rollno=b.rollno);

_____________________________________________________________________

Question: How to fetch all the records from Employee whose joining year is  2017?
Answer:
Oracle:
select * from Employee where To_char(Joining_date,’YYYY’)=’2017′;
MS SQL:
select * from Employee where substr(convert(varchar,Joining_date,103),7,4)=’2017′;
___________________________________________________________________________

Question:

sql> SELECT * FROM runners;
+----+--------------+
| id | name         |
+----+--------------+
|  1 | John Doe     |
|  2 | Jane Doe     |
|  3 | Alice Jones  |
|  4 | Bobby Louis  |
|  5 | Lisa Romero  |
+----+--------------+

sql> SELECT * FROM races;
+----+----------------+-----------+
| id | event          | winner_id |
+----+----------------+-----------+
|  1 | 100 meter dash |  2        |
|  2 | 500 meter dash |  3        |
|  3 | cross-country  |  2        |
|  4 | triathalon     |  NULL     |
+----+----------------+-----------+
What will be the result of the query below?
SELECT * FROM runners WHERE id NOT IN (SELECT winner_id FROM races)
Explain your answer and also provide an alternative version of this query that will avoid the issue that it exposes.

Surprisingly, given the sample data provided, the result of this query will be an empty set. The reason for this is as follows: If the set being evaluated by the SQL NOT IN condition contains any values that are null, then the outer query here will return an empty set, even if there are many runner ids that match winner_ids in the races table.
Knowing this, a query that avoids this issue would be as follows:
SELECT * FROM runners WHERE id NOT IN (SELECT winner_id FROM races WHERE winner_id IS NOT null)

Note, this is assuming the standard SQL behavior that you get without modifying the default ANSI_NULLS setting.
_________________________________________________________________________

Question : How would you create a list or a table from scratch in a database where you dont have write permission.

Answer: Use the With Clause

With Table1 As(
select 'MLCF02353' As C1,'Thalam' As Names from dual union
select 'ICBNY0061', 'Abhishek' from dual union
select 'BNPN.02E9','Roza' from dual
 )


 select * from table1

_________________________________________________________________________

Question : Extract the first name, last name from a full name

Answer:

with table_A as
(
select 'Abhishek Rath' as Full_name from dual union all
select 'Piyush Gangwar ' as Full_name from dual union all
select 'kabita Ghosh' as Full_name from dual union all
select 'Nimisha Jain ' as Full_name from dual union all
Select 'Pranav Thale' as Full_name from dual
)

select Full_name,
SUBSTR(Full_name,0,INSTR(TRIM(Full_name),' ')- 1) AS first_name,

SUBSTR(full_name,INSTR(TRIM(full_name),' ',-1)+ 1) AS last_name  from table_A


_______________________________________________________________________________

Question : Extract 

Answer :

Assuming you requirement is something like..

FIRST_NAME : The first word in your full name
LAST_NAME  : The last Word in the Full Name excluding the SUFFIX (if present)
MID_NAME    : The entire set of word between FIRST_NAME and LAST_NAME
SUFFIX             : The word / letters after the last comma

WITH NAMES(FULL_NAME) AS(
         SELECT 'ABC DEF GHI JKL, MN'    FROM DUAL UNION ALL
         SELECT 'OPQ RST, UV'                      FROM DUAL UNION ALL
         SELECT 'WXY Z'                                  FROM DUAL UNION ALL
         SELECT 'Ronald V. McDonald, DO' FROM DUAL UNION ALL
         SELECT 'Fred Derf, DD'                     FROM DUAL UNION ALL
         SELECT 'Pig Pen'                                 FROM DUAL )
SELECT  FULL_NAME
        ,SUBSTR(FULL_NAME,0,INSTR(FULL_NAME,' ')-1) AS FIRST_NAME
        ,CASE WHEN (REGEXP_COUNT(FULL_NAME,',')=0) AND (REGEXP_COUNT(FULL_NAME,' ')>1)
                             THEN SUBSTR(FULL_NAME, INSTR(FULL_NAME,' ',1)+1, INSTR(FULL_NAME, ' ',-1)-1)
                    WHEN (REGEXP_COUNT(FULL_NAME,',')>0) AND (REGEXP_COUNT(SUBSTR(FULL_NAME,1,INSTR(FULL_NAME,',', -1)-1),' ')>1)
                             THEN REGEXP_REPLACE(SUBSTR(REGEXP_SUBSTR(FULL_NAME, ' (.*?),'), 1, INSTR(REGEXP_SUBSTR(FULL_NAME, ' (.*?),'),' ',-1)),'[[:punct:]]')
                    ELSE NULL END AS MID_NAME
        ,CASE WHEN REGEXP_COUNT(FULL_NAME,',')=0
                             THEN SUBSTR(FULL_NAME, INSTR(FULL_NAME,' ',-1)+1)
                    ELSE SUBSTR(SUBSTR(FULL_NAME,1,INSTR(FULL_NAME,',',-1)-1), INSTR(SUBSTR(FULL_NAME,1,INSTR(FULL_NAME,',',-1)-1),' ',-1)+1) END AS LAST_NAME
        ,CASE WHEN REGEXP_COUNT(FULL_NAME,',')>0
                              THEN SUBSTR(FULL_NAME,INSTR(FULL_NAME,',',-1)+1)
                    ELSE NULL END AS SUFFIX
FROM  NAMES;

FULL_NAME
FIRST_NAME
MID_NAME
LAST_NAME
SUFFIX
ABC DEF GHI JKL, MNABCDEF GHIJKLMN
OPQ RST, UVOPQ-RSTUV
WXY ZWXY-Z-
Ronald V. McDonald, DORonaldVMcDonaldDO
Fred Derf, DDFred-DerfDD
Pig PenPig-Pen-

_______________________________________________________________________________

Question: INSTR Function explained with examples (https://www.databasestar.com/oracle-instr/)

Question: Regular Expression explained with examples (https://www.databasestar.com/oracle-regexp-functions/)

_______________________________________________________________________________

Question: Print all the dates from past x number of months or x number of days till today.

Answer:

select
   to_date(to_CHAR(ADD_MONTHS(TRUNC(SYSDATE), -3),'dd/mm/yyyy'),'dd-mm-yyyy') + rownum -1 AS DAY
from
   all_objects -- All objects table is used as it has a lot of records.
where
   rownum <=   to_date(TO_CHAR(SYSDATE,'DD/MM/YYYY'),'DD/MM/YYYY')-to_date(to_CHAR(ADD_MONTHS(TRUNC(SYSDATE), -3),'dd/mm/yyyy'),'dd-mm-yyyy')+1
_______________________________________________________________________________
Question :

Table A

Table B

1

1

2

2

1

3

3

4

4

4

5

4



What is the Output of Left Join and Inner join

_______________________________________________________________________________

Question :

Name

Subject

Marks

Grade

Range

Ravi

Maths

70

A

80>=

Sandeep

English

80

B

70-79

Rahul

Science

65

C

60-69

Sakshi

SST

76

D

<60

Swati

Computers

84

Ramesh

Accounting

55

What is the count of total students having grades A to D

_______________________________________________________________________________

Question:

abhishekrath@ubs.com
akankshakapoor@mastercard.com
rahul.gandhi@congress.com


Write a query to display only the domains

_______________________________________________________________________________


Question:

Select col1,col2 from table group by col1
Select col1 from table group by col1,col2
select col1,col2 from table group by col1,col2

Which one will give error?

_______________________________________________________________________________

Question:

with rws as (
  select 'split,into,rows' str from dual
)
  select regexp_substr (
           str,
           '[^,]+',
           1,
           level
         ) value
  from   rws
  connect by level <= 
    length ( str ) - length ( replace ( str, ',' ) ) + 1;
 
Output
--------
   
VALUE   
split    
into     
rows



So what's going on here?

The connect by level clause generates a row for each value. It finds how many values there are by:

  • Using replace ( str, ',' ) to remove all the commas from the string
  • Subtracting the length of the replaced string from the original to get the number of commas
  • Add one to this result to get the number of values

The regexp_substr extracts each value using this regular expression:

[^,]+

This searches for:

  • Characters not in the list after the caret. So everything except a comma.
  • The plus operator means it must match one or more of these non-comma characters

The third argument tells regexp_substr to start the search at the first character. And the final one instructs it to fetch the Nth occurrence of the pattern. So row one finds the first value, row two the second, and so on.


_______________________________________________________________________________

Question:

Given the following table:

ORDER_DATEPRODUCT_IDQTY
2007/09/25100020
2007/09/26200015
2007/09/2710008
2007/09/28200012
2007/09/2920002
2007/09/3010004

I need the Output in the following format:

PRODUCT_IDORDER_DATENEXT_ORDER_DATE
10002007/09/252007/09/26
20002007/09/262007/09/27
10002007/09/272007/09/28
20002007/09/282007/09/29
20002007/09/292007/09/30
10002007/09/30NULL


Answer:
SELECT product_id, order_date,
LEAD (order_date,1) OVER (ORDER BY order_date) AS next_order_date
FROM orders;

In this example, the LEAD function will sort in ascending order all of the order_date values in the orders table and then return the next order_date since we used an offset of 1.

If we had used an offset of 2 instead, it would have returned the order_date from 2 orders later. If we had used an offset of 3, it would have returned the order_date from 3 orders later....and so on.

Using Partitions

Now let's look at a more complex example where we use a query partition clause to return the next order_date for each product_id.

Enter the following SQL statement:

SELECT product_id, order_date,
LEAD (order_date,1) OVER (PARTITION BY product_id ORDER BY order_date) AS next_order_date
FROM orders;

It would return the following result:

PRODUCT_IDORDER_DATENEXT_ORDER_DATE
10002007/09/252007/09/27
10002007/09/272007/09/30
10002007/09/30NULL
20002007/09/262007/09/28
20002007/09/282007/09/29
20002007/09/29NULL

In this example, the LEAD function will partition the results by product_id and then sort by order_date as indicated by PARTITION BY product_id ORDER BY order_date. This means that the LEAD function will only evaluate an order_date value if the product_id matches the current record's product_id. When a new product_id is encountered, the LEAD function will restart its calculations and use the appropriate product_id partition.

As you can see, the 3rd record in the result set has a value of NULL for the next_order_date because it is the last record for the partition where product_id is 1000 (sorted by order_date). This is also true for the 6th record where the product_id is 2000.

_______________________________________________________________________________

Question

https://techtfq.com/blog/practice-sql-interview-query-big-4-interview-question#google_vignette

-->> Problem Statement:
Write a query to fetch the record of brand whose amount is increasing every year.


-->> Dataset:
drop table brands;
create table brands
(
    Year    int,
    Brand   varchar(20),
    Amount  int
);
insert into brands values (2018, 'Apple', 45000);
insert into brands values (2019, 'Apple', 35000);
insert into brands values (2020, 'Apple', 75000);
insert into brands values (2018, 'Samsung', 15000);
insert into brands values (2019, 'Samsung', 20000);
insert into brands values (2020, 'Samsung', 25000);
insert into brands values (2018, 'Nokia', 21000);
insert into brands values (2019, 'Nokia', 17000);
insert into brands values (2020, 'Nokia', 14000);

-------------------------------------------------------------------------------------------------
-->> Solution:

with cte as
    (select *
    , (case when amount < lead(amount, 1, amount+1)
                                over(partition by brand order by year)
                then 1
           else 0
      end) as flag
    from brands)
select *
from brands
where brand not in (select brand from cte where flag = 0)

Or (My answer)

WITH CTE AS(

Select a.*,lead(amount)  over(partition by brand order by year),
case 
    when amount< lead(amount)  over(partition by brand order by year) THEN 1 
    when lead(amount)  over(partition by brand order by year) IS NULL THEN 1
    ELSE 0 END AS FLAG
from brands a
)

Select YEAR, BRAND, AMOUNT
FROM CTE
WHERE BRAND NOT IN (Select BRAND from CTE where FLAG = 0)

_______________________________________________________________________________

Scenario-

Q) How to get the first day and the last day of any month in Oracle SQL

A) SELECT TRUNC(SYSDATE, 'MM') AS first_day_of_mnth, LAST_DAY(SYSDATE) AS last_day_of_mnth
FROM dual;




Tuesday, July 4, 2017

Hadoop Basics




HADOOP:


Hadoop has two major components HDFS and MapReduce. HDFS is storage and MapReduce is programming framework.


Hadoop is a framework which allows us to perform perform parallel and distributed computations on large data sets. Hadoop has fundamentally two units - storage and processing. You get HDFS as a storage service with Hadoop to store large data sets. Basically, HDFS is a distributed file system that allows you to store large file across the Hadoop cluster.


 


Hadoop Common: The common utilities that support the other Hadoop modules.


Hadoop Distributed File System (HDFS): A distributed file system that provides high-throughput access to application data.


Hadoop YARN: A framework for job scheduling and cluster resource management.


Hadoop MapReduce: A YARN-based system for parallel processing of large data sets.


 


APACHE SPARK:


Spark is another execution framework. Like MapReduce, it works with the file system to distribute your data across the cluster, and process that data in parallel. Like MapReduce, it also takes a set of instructions from an application written by a developer. MapReduce was generally coded from Java; Spark supports not only Java, but also Python and Scala, which is a newer language that contains some attractive properties for manipulating data.


 


What are the Spark use cases?


Databricks (a company founded by the creators of Apache Spark) lists the following cases for Spark:


  • Data integration and ETL
  • Interactive analytics or business intelligence
  • High performance batch computation
  • Machine learning and advanced analytics
  • Real-time stream processing
     
    SCALA:
    Scala is an acronym for “Scalable Language”. To some, Scala feels like a scripting language. Its syntax is concise and low ceremony; its types get out of the way because the compiler can infer them.
    Scala is a pure-bred object-oriented language. Conceptually, every value is an object and every operation is a method-call.
    The language supports advanced component architectures through classes and traits.
    Many traditional design patterns in other languages are already natively supported. For instance, singletons are supported through object definitions and visitors are supported through pattern matching.
    Using implicit classes, Scala even allows you to add new operations to existing classes, no matter whether they come from Scala or Java!
     
    HIVE:
    Apache Hive is considered the defacto standard for interactive SQL queries over petabytes of data in Hadoop.
    Hadoop was built to organize and store massive amounts of data of all shapes, sizes and formats. Because of Hadoop’s “schema on read” architecture, a Hadoop cluster is a perfect reservoir of heterogeneous data—structured and unstructured—from a multitude of sources.
    Data analysts use Hive to query, summarize, explore and analyze that data, then turn it into actionable business insight.
     


Feature
Description
Familiar
Query data with a SQL-based language
Fast
Interactive response times, even over huge datasets
Scalable and Extensible
As data variety and volume grows, more commodity machines can be added, without a corresponding reduction in performance
Compatible
Works with traditional data integration and data analytics tools.


 


  • The tables in Hive are similar to tables in a relational database, and data units are organized in a taxonomy from larger to more granular units. Databases are comprised of tables, which are made up of partitions. Data can be accessed via a simple query language and Hive supports overwriting or appending data.
  • Within a particular database, data in the tables is serialized and each table has a corresponding Hadoop Distributed File System (HDFS) directory. Each table can be sub-divided into partitions that determine how data is distributed within sub-directories of the table directory. Data within partitions can be further broken down into buckets.
  • Hive supports all the common primitive data formats such as BIGINT, BINARY, BOOLEAN, CHAR, DECIMAL, DOUBLE, FLOAT, INT, SMALLINT, STRING, TIMESTAMP, and TINYINT. In addition, analysts can combine primitive data types to form complex data types, such as structs, maps and arrays.
     
    MONGO DB:


  • MongoDB stores data in flexible, JSON-like documents, meaning fields can vary from document to document and data structure can be changed over time
  • The document model maps to the objects in your application code, making data easy to work with
  • Ad hoc queries, indexing, and real time aggregation provide powerful ways to access and analyze your data
  • MongoDB is a distributed database at its core, so high availability, horizontal scaling, and geographic distribution are built in and easy to use
  • MongoDB is free and open-source, published under the GNU Affero General Public License
     
     
     

Friday, April 7, 2017

Save raw data in a sheet in existing excel workbook

I want to import a CSV file and save it in a Sheet in my existing excel workbook






Sub ImportRawData()


'Import Raw data


Const strFileName = "C:\Data\RawData.xlsx" '<<--Change this secotion for all region
    Dim wbkS As Workbook
    Dim wshS As Worksheet
    Dim wshT As Worksheet
   
    'Delete any Raw Data  if present previously.
    Application.DisplayAlerts = False
    For Each Sheet In ActiveWorkbook.Worksheets
          If Sheet.Name = "RawData" Then
          Sheet.Delete
          End If
    Next Sheet
    Application.DisplayAlerts = True
   
    'Insert RawData to new sheet
    Set wshT = Worksheets.Add(After:=Worksheets(Worksheets.Count))
    Set wbkS = Workbooks.Open(Filename:=strFileName)
    Set wshS = wbkS.Worksheets(1)
    wshS.UsedRange.Copy Destination:=wshT.Range("A1")
    wbkS.Close SaveChanges:=False
    ActiveSheet.Name = "RawData"
   
    'Save the Last Row and Last Column of raw Data into a varible
   
    Dim lC As Long
    Dim LR As Long
    With ThisWorkbook.Sheets("RawData")
        lC = .Cells(1, .Columns.Count).End(xlToLeft).Column
        LR = .Cells(.Rows.Count, "A").End(xlUp).Row
    End With
   
    'Secretly save the values in a location in Automation sheet invisible to users.
   
    Sheets("Automation").Select
    ThisWorkbook.Sheets("Automation").Range("B34").Value = lC
    ThisWorkbook.Sheets("Automation").Range("B36").Value = LR
    Sheets("Automation").Select
      
End Sub

Finding difference two columns untill empty cells encountered


This piece of code will find difference between two column until it finds empty cell.




Sheets("Collateral Type Codes").Select
Sheets("Collateral Type Codes").Cells(3, 7).Value = "Difference"
For i = 4 To 100000
If IsEmpty(Sheets("Collateral Type Codes").Cells(i, 2)) Then
GoTo Label2
End If
Sheets("Collateral Type Codes").Cells(i, 7).Value = Sheets("Collateral Type Codes").Cells(i, 3).Value - Sheets("Collateral Type Codes").Cells(i, 4).Value
Next i

Label2:
ActiveSheet.Range("G3").Select
    Selection.AutoFilter
    ActiveSheet.Columns("D:D").AutoFilter Field:=1, Criteria1:="<>0", Operator:=xlFilterValues

Creating a Pivot table using VBA

We are trying to create a vba script, where we are taking input for the Row lable, Column label,  and Value field from a metadata sheet. The Raw data is a separate sheet from which we are generating the pivots.


Below are the steps:




Sub CreatePivot()


Dim PSheet As Worksheet
Dim DSheet As Worksheet
Dim PCache As PivotCache
Dim PTable As PivotTable
Dim PRange As Range
Dim lastRow As Long
Dim lastCol As Long



'Delete Preivous Pivot Table Worksheet &amp; Insert a New Blank


Worksheet With Same Name
On Error Resume Next
Application.DisplayAlerts = False
Worksheets("Collateral Type Codes").Delete
Sheets("RawData").Select
Sheets.Add After:=ActiveSheet
ActiveSheet.Name = "Collateral Type Codes"
Application.DisplayAlerts = True
Set PSheet = Worksheets("Collateral Type Codes")
Set DSheet = Worksheets("RawData")



'Define Data Range


lastRow = DSheet.Cells(Rows.Count, 1).End(xlUp).Row
lastCol = DSheet.Cells(1, Columns.Count).End(xlToLeft).Column
Set PRange = DSheet.Cells(1, 1).Resize(lastRow, lastCol)



'Define Pivot Cache


Set PCache = ActiveWorkbook.PivotCaches.Create _
(SourceType:=xlDatabase, SourceData:=PRange). _
CreatePivotTable(TableDestination:=PSheet.Cells(2, 2), _
TableName:="MerivalPivotTable")

Dim Col1 As String
Dim Row1 As String
Dim RowArray() As String
Dim ColArray() As String
Dim Value As String
Dim ValueArray() As String
Dim Func

Row1 = Sheets("PivotMetaData").Cells(6, 3).Value
Col1 = Sheets("PivotMetaData").Cells(6, 4).Value
Value = Sheets("PivotMetaData").Cells(6, 5).Value
Func = Sheets("PivotMetaData").Cells(6, 6).Value

RowArray = Split(Row1, ",")
ColArray = Split(Col1, ",")
ValArray = Split(Value, ",")
Set PTable = PCache.CreatePivotTable(TableDestination:=PSheet.Cells(1, 1), TableName:="MerivalPivotTable")



'Insert Row Fields


For i = 0 To UBound(RowArray)
With ActiveSheet.PivotTables("MerivalPivotTable").PivotFields(RowArray(i))
 .Orientation = xlRowField
 .Position = i + 1
End With
Next I



'Insert Column Fields


For j = 0 To UBound(ColArray)
With ActiveSheet.PivotTables("MerivalPivotTable").PivotFields(ColArray(j))
 .Orientation = xlColumnField
 .Position = j + 1
End With
Next j



'Insert Data Field


If Func = "Sum" Then
For k = 0 To UBound(ValArray)
With ActiveSheet.PivotTables("MerivalPivotTable").PivotFields(ValArray(k))
 .Orientation = xlDataField
 .Position = k + 1
 .Function = xlSum
 .NumberFormat = "#,##0"
 End With
Next k
End If



If Func = "Count" Then
For k = 0 To UBound(ValArray)
With ActiveSheet.PivotTables("MerivalPivotTable").PivotFields(ValArray(k))
 .Orientation = xlDataField
 .Position = k + 1
 .Function = xlCount
 .NumberFormat = "#,##0"
 End With
Next k
End If



If Func = "Average" Then
For k = 0 To UBound(ValArray)
With ActiveSheet.PivotTables("MerivalPivotTable").PivotFields(ValArray(k))
 .Orientation = xlDataField
 .Position = k + 1
 .Function = xlAverage
 .NumberFormat = "#,##0"
 End With
Next k
End If



If Func = "Max" Then
For k = 0 To UBound(ValArray)
With ActiveSheet.PivotTables("MerivalPivotTable").PivotFields(ValArray(k))
 .Orientation = xlDataField
 .Position = k + 1
 .Function = xlMax
 .NumberFormat = "#,##0"
End With
Next k
End If



If Func = "Min" Then
For k = 0 To UBound(ValArray)
With ActiveSheet.PivotTables("MerivalPivotTable").PivotFields(ValArray(k))
 .Orientation = xlDataField
 .Position = k + 1
 .Function = xlMin
 .NumberFormat = "#,##0"
End With
Next k
End If



If Func = "Product" Then
For k = 0 To UBound(ValArray)
With ActiveSheet.PivotTables("MerivalPivotTable").PivotFields(ValArray(k))
 .Orientation = xlDataField
 .Position = k + 1
 .Function = xlProduct
 .NumberFormat = "#,##0"
End With
Next k

End If

How to export few sheets of current workbook into a new workbook:

Here we are trying to export few sheets from our current workbook and save it in a new workbook. The new workbook should automatically replace any already available workbook (if present).


Sub ExportSheets()


Application.DisplayAlerts = False
ThisWorkbook.Sheets(Array("Sheet1", "Sheet2", "Sheet3")).Move
ActiveWorkbook.SaveAs "
C:\users\AB\NewWorkbook.xlsx", FileFormat:=51, AccessMode:=xlExclusive, ConflictResolution:=Excel.XlSaveConflictResolution.xlLocalSessionChanges
ActiveWorkbook.Close (True)



End Sub


Here we are using the move option, which means it will cut the sheets from the existing workbook and paste it in a new workbook and save it by the name NewWorkbook.xlsx.


The clause :
ConflictResolution:=Excel.XlSaveConflictResolution.xlLocalSessionChanges
ensures that the sheet will always overwrite any existing file by the same name.


And as we are keeping Application.DisplayAlerts = False
Excel will not prompt users with messages.

Tuesday, April 4, 2017

Import a CSV file into excel without User prompt

I was working in an end to end automation project, where I required to import a CSV file into my existing excel workbook and name it Raw Data. based on this Raw Data sheet I intend to Draw multiple pivots. This importing of CSV and generating pivots required to be iterated for nine different regions. This is a series of Blogs through which I shall be explaining the entire automation.


So without any much delay lets start with the initial part of importing of CSV file into our excel.


Sub ImportCSV()
   
    Const strFileName = "C:\Users\AB\Downloads\Sample.csv"
    Dim wbkS As Workbook
    Dim wshS As Worksheet
    Dim wshT As Worksheet
   
    'Delete any Raw Data if present previously.
    Application.DisplayAlerts = False
    For Each Sheet In ActiveWorkbook.Worksheets
          If Sheet.Name = "RawData" Then
          Sheet.Delete
          End If
    Next Sheet
    Application.DisplayAlerts = True
   
    'Insert RawData from Sample.csv
    Set wshT = Worksheets.Add(After:=Worksheets(Worksheets.Count))
    Set wbkS = Workbooks.Open(Filename:=strFileName)
    Set wshS = wbkS.Worksheets(1)
    wshS.UsedRange.Copy Destination:=wshT.Range("A1")
    wbkS.Close SaveChanges:=False
    ActiveSheet.Name = "RawData"
End Sub



By this code sample we are importing Sample.csv from a specified location and placing it in our existing workbook and naming the sheet as RawData. We basically opening Sample.csv, copying data from it and then closing it.




Checking if the CSV file exists of not:





Sub ImportCSV()
   
    Const strFileName = "C:\Users\AB\Downloads\Sample.csv"

 
    If Dir(strFileName) <> "" Then
   
       
    Dim wbkS As Workbook
    Dim wshS As Worksheet
    Dim wshT As Worksheet
   
    'Delete any Raw Data if present previously.
    Application.DisplayAlerts = False
    For Each Sheet In ActiveWorkbook.Worksheets
          If Sheet.Name = "RawData" Then
          Sheet.Delete
          End If
    Next Sheet
    Application.DisplayAlerts = True
   
    'Insert RawData from Sample.csv
    Set wshT = Worksheets.Add(After:=Worksheets(Worksheets.Count))
    Set wbkS = Workbooks.Open(Filename:=strFileName)
    Set wshS = wbkS.Worksheets(1)
    wshS.UsedRange.Copy Destination:=wshT.Range("A1")
    wbkS.Close SaveChanges:=False
    ActiveSheet.Name = "RawData"
     
   
Else
    Exit Sub
End If
      
End Sub