Open CSV file in background and retrieve worksheet name - vba

My VBA project consists on cleaning databases.
I'm using a Userform, and this is the code i wrote till now.
I have been successful at importing a file, but i still can't perform actions on it.
I need you guys to show me how can i get the workbook name and worksheets of the .csv file i just imported to start assigning actions referring to the database by its workbook name and worksheet name.
I'd also appreciate it if you can show me how to keep my userform on top, or how to import the .csv file without displaying it
code
Dim fNameAndPath As Variant
Private Sub importedworkbook_Click()
MsgBox "imported workbook : " & _
fNameAndPath
End Sub
Private Sub Importbutton_Click()
fNameAndPath = Application.GetOpenFilename(FileFilter:="CSV Files Only (*.CSV), *.XLS", Title:="Select File To Be Opened")
If fNameAndPath = False Then Exit Sub
Workbooks.Open Filename:=fNameAndPath
End Sub

Best to use declared variables to reference the opened CSV sheet
Private wsCSV as Worksheet
Private Sub Importbutton_Click()
Dim wb as Workbook
fNameAndPath = Application.GetOpenFilename(FileFilter:="CSV Files Only (*.CSV), *.XLS", Title:="Select File To Be Opened")
If fNameAndPath = False Then Exit Sub
Set wb = Workbooks.Open(Filename:=fNameAndPath)
Set wsCSV = wb.Worksheets(1) ' A csv file will only ever have one sheet
End Sub
Variable wsCSV now refers to the CSV sheet, and can be referenced in other code in the UserForm module

You can open a second instance of Excel to work with the hidden file
Dim objExcel As Excel.Application
Dim wb As Workbook
fNameAndPath = Application.GetOpenFilename(FileFilter:="CSV Files Only (*.CSV), *.XLS", Title:="Select File To Be Opened")
If fNameAndPath = False Then Exit Sub
Set objExcel = New Excel.Application
Set wb = objExcel.Workbooks.Open(fNameAndPath)
Set wsCSV = wb.Worksheets(1)
MsgBox wsCSV.Name
' do stuff
'close second instance
wb.Close False
objExcel.Quit
Set objExcel = Nothing

Related

VBA open file in active worksheet

I am trying to create a code to open an Excel file (CSV file actually) in the active worksheet of a workbook. The file is not always located on the same location and does not always have the same name. Therefore I want the user to be able to browse the file.
I tried the code shown below. The code works partially, the code now opens the file in a new workbook. However, I would like to open the file/get the data in the active worksheet. Do you know how I could change the code to do this?
Sub OpenFile()
Dim FileName As String, test As Workbook
On Error GoTo ErrorMessage
FileName = Application.GetOpenFilename(, , "Browse for workbook")
'Open workbook
Workbooks.Open FileName
Set test = ActiveWorkbook
Exit Sub
ErrorMessage:
MsgBox ("Je hebt geen bestand geselecteerd, probeer het nogmaals.")
End Sub
You could just open the file copy the cells to the target worksheet.
Sub OpenFile()
Dim FileName As String
FileName = Application.GetOpenFilename("Comma Separated Values,*.csv", , "Browse for workbook")
If FileName = "False" Then Exit Sub
Dim TargetWorksheet As Worksheet
Set TargetWorksheet = ActiveSheet
Application.ScreenUpdating = False
With Workbooks.Open(FileName)
ActiveSheet.UsedRange.Copy TargetWorksheet.Range("A1")
.Close SaveChanges:=False
End With
End Sub
You could open the workbook the user selects and copy whatever sheet you need into your current workbook. Edit: This will paste it into your active sheet using UsedRange as others have shown.
Sub OpenFile()
Application.ScreenUpdating = False
Dim FileName As String, test As Workbook
Dim shActive As Worksheet
On Error GoTo ErrorMessage
FileName = Application.GetOpenFilename(, , "Browse for workbook")
'Open workbook
Set shActive = ActiveSheet
Set test = Workbooks.Open(FileName)
'copy the sheet you need from that workbook into your current workbook
test.Sheets(1).UsedRange.Copy shActive.Range("A1")
'close the previous workbook
test.Close SaveChanges:=False
Exit Sub
ErrorMessage:
MsgBox ("Je hebt geen bestand geselecteerd, probeer het nogmaals.")
End Sub

Vba code to open multiple files in separate sheets of the same workbook

I have a code that allows me to open a file in an excel workbook, however I want to be able to open multiple files within the same workbook named p00001, p00002, p00003 and so on. Does anyone know how I can edit my code to select all the files named this way and open them in separate sheets in the same workbook?
My code is:
Sub Open_Workbook()
Dim my_FileName As Variant
my_FileName = Application.GetOpenFilename
If my_FileName <> False Then
Workbooks.Open Filename:=my_FileName
End If
End Sub
In this solution i used the FileDialog for Selecting Multiple Files.
After that, you need to Loop all thoes Files a for Loop.
Inside the For Loop, you have to Open the File and Import the Sheet. In this Example i Imported all the Sheets the Workbook has.
After the Code is done Importing you close the Source Workbook and do the Same for the Rest of the Files.
Sub Import Files()
Dim sheet As Worksheet
Dim total As Integer
Dim intChoice As Integer
Dim strPath As String
Dim i As Integer
Dim wbNew As Workbook
Dim wbSource As Workbook
Set wbNew = Workbooks.Add
'allow the user to select multiple files
Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = True
'make the file dialog visible to the user
intChoice = Application.FileDialog(msoFileDialogOpen).Show
Application.ScreenUpdating = False
Application.DisplayAlerts = False
'determine what choice the user made
If intChoice <> 0 Then
'get the file path selected by the user
For i = 1 To Application.FileDialog(msoFileDialogOpen).SelectedItems.Count
strPath = Application.FileDialog(msoFileDialogOpen).SelectedItems(i)
Set wbSource = Workbooks.Open(strPath)
For Each sheet In wbSource.Worksheets
total = wbNew.Worksheets.Count
wbSource.Worksheets(sheet.Name).Copy _
after:=wbNew.Worksheets(total)
Next sheet
wbSource.Close
Next i
End If
End Sub
If you want to get all Files From a Directory you can change the ApplicationFile Dialog with a Loop were you Loop the Directory Like This:
directory = "c:\test\"
fileName = Dir(directory & "*.xl??")
Do While fileName <> ""
'Put Code From For Loop here.
Loop

VBA how to open a excel file and tell its creation date

I am trying to open a file from somewhere and also get the date when the opened file was created. However the line below gives me an error "Run Time Error, Automation error and Unspecified error". How can I fix this? Thanks.
MsgBox wb2.BuiltinDocumentProperties("Creation Date")
Private Sub CommandButton1_Click()
Dim wb1 As Workbook, wb2 As Workbook
Dim Ret1, Ret2
Dim WS As Worksheet
Set wb1 = ActiveWorkbook
'Clear Summary tab
wb1.Worksheets("Summary").Cells.Clear
'Delete existing worksheet with name "Task List Data Export"
For Each WS In Worksheets
If WS.Name = "Task List Data Export" Then
Application.DisplayAlerts = False
Sheets("Task List Data Export").Delete
Application.DisplayAlerts = True
End
End If
Next
'Get the File
Ret1 = Application.GetOpenFilename("Excel Files (*.xls*), *.xls*", _
, "Please select file")
If Ret1 = False Then Exit Sub
'Copy file
Set wb2 = Workbooks.Open(Ret1)
MsgBox wb2.BuiltinDocumentProperties("Creation Date")
wb2.Sheets(1).Select
wb2.Sheets(1).Copy After:=wb1.Sheets(2)
'Close opened file
wb2.Close savechanges:=False
Set wb2 = Nothing
Worksheets("Cover").Activate
End Sub
If Microsoft Excel doesn’t define a value for one of the built-in document properties, reading the Value property for that document property causes an error.
From Workbook.BuiltinDocumentProperties Property
There is always a file created date and hence it is quite surprising that you are getting that error. I have never got this error. Even a newly created file which has not been saved gives you a "File Created Date and Time".
Here is an alternative.
Dim CtdDate As String
Dim fs As Object, f As Object
Ret1 = Application.GetOpenFilename("Excel Files (*.xls*), *.xls*", _
, "Please select file")
If Ret1 = False Then Exit Sub
Set fs = CreateObject("Scripting.FileSystemObject")
Set f = fs.GetFile(Ret1)
CtdDate = f.DateCreated
Set wb2 = Workbooks.Open(Ret1)
MsgBox CtdDate

copy information to an external workbook

I am writing a macro where I take data from a CSV and copy it to another Excel file (not the current or active file).
What is the code to take the copied data and send it to another file in the same directory.
This is my code, I have commented out the lines that cause the macro not to work. I want to set the variable wshT to Sheet1 of the WTF.xlsx file, which is in the same directory but not the active workbook. I have not opened that one. So the goal is to use this macro to copy extra data from the CSV and send it to the WTF.xlsx file and save it as something new, in this case "BBB". Any help is much appreciated. When I uncomment those lines, errors pop up.
Sub Import()
Dim MyPath As String
Dim strFileName As String
'Dim strFileName1 As String
MyPath = ActiveWorkbook.Path
strFileName = MyPath & "\borgwich_die_BM1940_profile.csv"
'strFileName1 = Workbooks("WTF.xlsx").Activate
'strFileName1 = Workbooks("WTF.xlsx").Worksheets("Sheet1").Select
Dim wbkS As Workbook
Dim wshS As Worksheet
Dim wshT As Worksheet
'Set wshT = strFileName1
Set wbkS = Workbooks.Open(Filename:=strFileName)
Set wshS = wbkS.Worksheets(1)
wshS.Range("A1:A3").EntireRow.Delete
'wshS.UsedRange.Copy Destination:=wshT.Range("A1")
wbkS.Close SaveChanges:=False
Application.DisplayAlerts = False
ActiveWorkbook.SaveAs Filename:=MyPath & "\BBB", FileFormat _
:=51, CreateBackup:=False
Application.DisplayAlerts = False
'ActiveWindow.Close
End Sub
Your use of value assignment to strFileName1 through the use of .Activate and/or .Select was bad methodology. If WTF.xlsx is open, you can directly reference its Sheet1 and Set a worksheet object reference to a variable.
Sub Import()
Dim MyPath As String, strFileName As String
Dim wbkS As Workbook, wshS As Worksheet, wshT As Worksheet
MyPath = ActiveWorkbook.Path
strFileName = MyPath & "\borgwich_die_BM1940_profile.csv"
Set wbkS = Workbooks.Open(Filename:=strFileName)
Set wshS = wbkS.Worksheets(1)
Set wshT = Workbooks("WTF.xlsx").Worksheets("Sheet1")
wshS.Range("A1:A3").EntireRow.Delete
With wshS.Cells(1, 1).CurrentRegion
.Copy Destination:=wshT.Range("A1")
End With
wbkS.Close SaveChanges:=False
Application.DisplayAlerts = False
wshT.Parent.SaveAs Filename:=MyPath & "\BBB", FileFormat:=51, CreateBackup:=False
wshT.Parent.Close SaveChanges:=False
Application.DisplayAlerts = True
End Sub
Another alternative would be to use the VBA equivalent of Data ► Get External Data ► From Text but you should probably know the number and type of fields being brought in with the CSV beforehand. This is certainly the preferred method if the CSV data is being incorrectly interpreted by the temp worksheet you are creating by opening the CSV as a workbook.

Workbook not activating in Excel by passing as an argument

I have a Book1.xls Excel workbook which has a macro written so that on workbook open the macro runs.
This macro takes all the CSV files in the workbook path and merges all the CSV into a single sheet say Master.xlsx which works fine and creates the Master.xlsx.
At the end of this macro I am calling another macro written in a module of same sheet and passing the Master.xlsx reference as workbook argument to another macro
Now what I want is that I need to set Master.xlsx passed an argument to this macro(module) as the current/active workbook so that I can format contents of the master.xlsx
My Code for the Book1.xls is :
Private Sub Workbook_Open()
'Create Excel application instance
Dim xlApp As Object
Dim dt, masterpath, folderPath, fileName, dtFolder As String
Set xlApp = CreateObject("Excel.Application")
'Setup workbooks
Dim wb As Excel.Workbook
Dim wBM As Excel.Workbook
Dim Wk As Workbook
fileName = "C:\Master.xlsx"
'Create a new Workbook
Set Wk = Workbooks.Add
Application.DisplayAlerts = False
Wk.SaveAs fileName:=fileName
Wk.Close SaveChanges:=False
Application.DisplayAlerts = True
'Csv files folder
Dim CSVfolder As String
CSVfolder = masterpath
'Master Excel file path
Dim mF As String
mF = fileName 'Where your master file is
'open the master file
Set wBM = xlApp.Workbooks.Open(mF)
'search and open the client files
Dim fname As String
fname = Dir(CSVfolder & "\*.csv")
Do While fname <> ""
'open the client file
Set wb = xlApp.Workbooks.Open(CSVfolder & "\" & fname)
'copy the first sheet from client file to master file
wb.Sheets(1).Copy After:=wBM.Sheets(wBM.Sheets.count)
'save master file
wBM.Save
'close client file
wb.Close False
'move to next client file
fname = Dir()
Loop
xlApp.Visible = True
Set xlApp = Nothing
Call AnotherMacroInModuleOfSameWorkbook(wBM)
End Sub
Code for Macro in Module of same Workbook
Sub AnotherMacroInModuleOfSameWorkbook(wb As Workbook)
wb.Activate
MsgBox (wb.Name)
MsgBox (ActiveWorkbook.Name)
End Sub
Here I'm getting "Master.xlsx" for alert 1 and "Book1.xls" for alert 2
What I wanted was that since I am passing reference of the Master.xlsx from the above macro and then activating the Master.xlsx in the below macro, the alert 2 should have given "Master.xlsx" as alert.
Please help.
Thanks.
By changing this line, the Master sheet opens now, where it wasn't before. It was just accessing it. I tested using my own workbooks, and used your code as a base. However, I didn't use all of your code, being that I don't have those objects. So it's mostly tested. I did generate the same errors you got before solving with this line, so I'm very certain this solves your problem:
Set wBM = Application.Workbooks.Open(mF)
The problem there is that when you open it, the code will break and need to be continued. To solve that, you need to place the following line before opening the workbook.
Application.EnableCancelKey = xlDisabled
BE WARNED: If you do this, you will not be able to break your code if you generate an infinite loop.
Please see this article about how to deal with EnableCancelKey
You are also trying to open a .xlsx file, instead of .xlsm Include this with your file creation statements.
FileFormat:= _xlOpenXMLWorkbookMacroEnabled
I found an workaround for this issue.
I tried closing the Master file generated (wBM) and again open the master workbook using Workbooks(mF).Open which ultimately gave me the current workbook (Master) as Active workbook.
Phewww..!!!! Hard time
Here's snapshot of the current working code:
Private Sub Workbook_Open()
'Create Excel application instance
Dim xlApp As Object
Dim dt, masterpath, folderPath, fileName, dtFolder As String
Set xlApp = CreateObject("Excel.Application")
'Setup workbooks
Dim wb As Excel.Workbook
Dim wBM As Excel.Workbook
Dim Wk As Workbook
fileName = "C:\Master.xlsx"
'Create a new Workbook
Set Wk = Workbooks.Add
Application.DisplayAlerts = False
Wk.SaveAs fileName:=fileName
Wk.Close SaveChanges:=False
Application.DisplayAlerts = True
'Csv files folder
Dim CSVfolder As String
CSVfolder = masterpath
'Master Excel file path
Dim mF As String
mF = fileName 'Where your master file is
'open the master file
Set wBM = xlApp.Workbooks.Open(mF)
'search and open the client files
Dim fname As String
fname = Dir(CSVfolder & "\*.csv")
Do While fname <> ""
'open the client file
Set wb = xlApp.Workbooks.Open(CSVfolder & "\" & fname)
'copy the first sheet from client file to master file
wb.Sheets(1).Copy After:=wBM.Sheets(wBM.Sheets.count)
'save master file
wBM.Save
'close client file
wb.Close False
'move to next client file
fname = Dir()
Loop
'close the current workbook
wBM.Close False
xlApp.Visible = True
Set xlApp = Nothing
'setting the reference again
Set newfile = Workbooks.Open(mF)
MsgBox (newfile.Name)
MsgBox (ActiveWorkbook.Name)
'Call to another module
Call AnotherMacroInModuleOfSameWorkbook(wBM)
End Sub
These two lines did the trick:
'close the current workbook
wBM.Close False
'setting the reference again
Set newfile = Workbooks.Open(mF)
Thanks for all the answers.