Extracting certain cells from excel files in a specified directory - vba

I am a VBA novice and I am trying to write a code that will copy the following data from multiple csv files all stored in the same directory.
I need it to open each csv file
Check IF Row 8 in columns H through CA for any cells that have the value ="TotalLMP" (Sample: Cell H8="TotalLMP")
THEN copy the value from both Row 7 and Row 19 of any columns that have that value ="TotalLMP" in Row 8 in two new columns (Sample: SINCE H8="TotalLMP", COPY H7="100" AS COLUMN A, COPY H19 = "26.437" AS COLUMN B)
THEN copy the value from cell $A$9 in a third column (Sample: COPY A9="20100101" AS COLUMN C")
after finishing loop through each csv file close and go to next
Then in the new active worksheet in the blank excel file would store each value as follows:
.......A .............. B ................ C
1 .. 100 .... 26.437 .... 20100101
2 .. 200 .... 26.585 .... 20100101

Let me help you with the CSV looping for now since this is rather hard for a beginner. I'm sure you will figure out how to test for a value in row 8. If not, you can always ask for more help!
In order to do so, you will have to use the Microsoft Scripting Runtime.
I suggest placing all of the csv file you want to open in the same directory, and only those to avoid potential problems.
Open a new workbook and go to the VBE (ALT + F11). Create a new module. Click in this new module, then go to Tools > References> Microsoft Scripting Runtime. This will let it know it will have to use that module and its objects.
Save the workbook as an macro-enabled workbook (.xls or .xslm for newer versions) in the same directory as your CSV (or somewhere else...)
Then start coding:
Sub Import_all_Csv()
' Reference Needed: Microsoft Scripting Runtime
' Dim some pointers to know what objects you will be manipulating thereafter
Dim MyWs, CSV As Worksheet
Set MyWs = ActiveSheet ' Meaning you will have to run the macro from the spreadsheet you want to export to. Feel free to replace that
Dim wbCSV As Workbook
' Those are the objects that belong to the reference Microsoft Scripting Runtime
Dim oFSO As FileSystemObject
Dim oFld As Folder
Dim oFile As File
Dim File As String
' Initialize the FileSystemObject
Set oFSO = New FileSystemObject
' That will only work on windows so I'm adding an error handler to ignore it if need be
On Error Resume Next
ChDir ThisWorkbook.Path
On Error GoTo 0 ' I'm asking VBA to throw an error now
' Dialog box to select the first csv file (this will let you choose another directory everytime)
File = Application.GetOpenFilename("Comma Separated Values File (*.csv*), *.csv*")
If File = "False" Then
Exit Sub ' Quit the macro if user canceled
Else
' Else get the path of the parent folder of that file
Set oFld = oFSO.GetFolder(oFSO.GetParentFolderName(File))
End If
' Go through each file in that folder
For Each oFile In oFld.Files
' Only open the CSV files
If oFile.Type = "Microsoft Excel Comma Separated Values File" Then
' Open it and set the first sheet (There is only one anyway)
Set wbCSV = Workbooks.Open(oFile)
Set CSV = wbCSV.Sheets(1)
' ============================
' Do what you want to do Here
' THIS IS A PLACEHOLDER
' Example to copy value of H8 in the CSV file to A2 the destination worksheet so you can see how to point to the correct cells in both files
MyWs.cells(1,2).value = wCSV.cells(8,8).value
' End of what you want to do
' ============================
' Close the CSV file without savings changes before going through the next one
wbCSV.Close False
End If
Next oFile
End Sub
I hope this helps! Good luck learning more VBA!
Best,
Julien

Related

Running an Access ImportExport from vbs fails if vbs is executed from Excel vba - any idea?

I have an Excel file (file1) with a macro that has this line:
Shell "wscript " & SFilename, vbNormalFocus
Where "SFilename" is the name of a vbs file.
In the vbs file I have a line:
appAccess.DoCmd.RunSavedImportExport ("ImportMonthlyData")
Above this line there are several lines like:
appAccess.DoCmd.OpenQuery ("Insert Detail")
And there is a lot of Excel work going on in the vbs on Excel file2 (not the same file that contains the wscript macro.
When I run the vbs file by double-clicking the vbs in file explorer, everything works great.
When I run the macro from within the Excel file1 via the macro, the vbs fails on the ImportExport line. The failure is that it cannot file the sheet in Excel from which to importexport, and the sheet name displayed in the error message has a "$" at the end of it. I don't know if the "$" is something Access does all the time, because it works when I use file explorer or if the "$" is being added on because of some other reason. However, my guess is this is not the problem.
I believe the problem arises because the ImportExport is trying to find the sheet in Excel file1 instead of file2.
What do you think? And if this is the problem, how do I rectify it?
So, you are trying to import Excel data to Access? Why now run the whole thing using VBA, which is a lot less cryptic, and much more intuitive, compared to running batch scripts.
Below is generic code to import the data from specific worksheets in all EXCEL files (worksheet names are the same in all files) that are located within a single folder. All of the EXCEL files' worksheets with the same worksheet names must have the data in the same layout and format.
Dim strPathFile As String, strFile As String, strPath As String
Dim blnHasFieldNames As Boolean
Dim intWorksheets As Integer
' Replace 3 with the number of worksheets to be imported
' from each EXCEL file
Dim strWorksheets(1 To 3) As String
' Replace 3 with the number of worksheets to be imported
' from each EXCEL file (this code assumes that each worksheet
' with the same name is being imported into a separate table
' for that specific worksheet name)
Dim strTables(1 To 3) As String
' Replace generic worksheet names with the real worksheet names;
' add / delete code lines so that there is one code line for
' each worksheet that is to be imported from each workbook file
strWorksheets(1) = "GenericWorksheetName1"
strWorksheets(2) = "GenericWorksheetName2"
strWorksheets(3) = "GenericWorksheetName3"
' Replace generic table names with the real table names;
' add / delete code lines so that there is one code line for
' each worksheet that is to be imported from each workbook file
strTables(1) = "GenericTableName1"
strTables(2) = "GenericTableName2"
strTables(3) = "GenericTableName3"
' Change this next line to True if the first row in EXCEL worksheet
' has field names
blnHasFieldNames = False
' Replace C:\Documents\ with the real path to the folder that
' contains the EXCEL files
strPath = "C:\Documents\"
' Replace 3 with the number of worksheets to be imported
' from each EXCEL file
For intWorksheets = 1 To 3
strFile = Dir(strPath & "*.xls")
Do While Len(strFile) > 0
strPathFile = strPath & strFile
DoCmd.TransferSpreadsheet acImport, _
acSpreadsheetTypeExcel9, strTables(intWorksheets), _
strPathFile, blnHasFieldNames, _
strWorksheets(intWorksheets) & "$"
strFile = Dir()
Loop
Next intWorksheets
Apparently, Excel is looking in file2 for the worksheet. I'm not sure why, but as a work around, I simply copied the needed worksheet from file1 to file2, completed the necessary work and then deleted the worksheet.

VBA for MS Access: write to an excel file without opening, write to last row, save and close

I am using VBA in MS Access for the first time and cannot get the following right:
Launch an excel file (without actually opening the file), then write to the last row in the excel file, and then save the file (with the same path and name as before, essentially replace the previous file), then close the excel file.
Please assist! So far I can write to an excel file, but cannot save and close without closing the whole MS Access application.
If you could please give a sample of working code to do the above, I will tailor it for my requirements.
Thanks!
Christine
First of all, in order to update and save a file like you want to, you have to open it first- so it is a little confusing/contradictory when you say that you don't want to 'actually open' an excel file... I took it to meant that you just don't want the excel application showing- which you would want something like this:
Public Sub demoCode()
Dim excelApp As Excel.Application
Dim targetWB As Workbook
Dim targetRange As Range
'Create new Excel Application
Set excelApp = New Excel.Application
'Keep hidden
excelApp.Visible = False
'Have new Excel App open workbook
Set targetWB = excelApp.Workbooks.Open("C:\Filename.xlsm")
'Set targetRange to 1 row past the first sheet's usedrange
Set targetRange = targetWB.Sheets(1).Range(targetWB.Sheets(1).UsedRange.address)(targetWB.Sheets(1).UsedRange.Rows.Count + 1, 1)
'Paste # targetRange
'Close and save workbook
targetWB.Close (True)
'Close Excel App
excelApp.Quit
End Sub
Hope this helps,
TheSilkCode

Write the content of two Excel files in a third one

I'm very new to vba programming and I would like to know what is the best method to do the following operation : read data from two Excel files (from a particular column of each file) and write this data in a third Excel file, writing the data contained in the first file first then the data contained in the second file. The figure below illustrates what I want to do :
How can I do that on click on a command button, without opening the two first files (I mean I don't want the user to see them).
You need to make so
Workbooks.Open Filename:= "c:\myfile\FILE1.xls"FILE1.xls"
Workbooks.Open Filename:= "c:\myfile\FILE2.xls"
After you open the FILE1.xls and FILE.xls you can create or open FILE3.xls,
in this case we create the FILE3.xls
Dim wb As Workbook
Set wb = Workbooks.Add
After this you read the data in FILE1.xls and FILE2.xls, you can read with WHILE or other LOOP or you read with COPY and PASTE data in new file.
In this case we see the LOOP strategy.
Dim i as Integer
Dim value as String
i=0
value = value = Workbooks("FILE1.xls").Worksheets("sheet1")..Range("B:B").Cells(i, 1)
Workbooks("FILE1.xls").Worksheets("sheet1").Activate
while value <> ""
Workbooks("FILE1.xls").Worksheets(2).Range("A:A").Cells(i, 1) = value
value = value = Workbooks("FILE1.xls").Worksheets("sheet1")..Range("B:B").Cells(i, 1)
Wend
Repeat ste for "FILE2.xls" read data and write in "FILE3.xls"
and at the and you close
wb.SaveAs "c:\myfile\"FILE3.xls""
wb.Close
And close the read data file
Workbooks("FILE1.xls").Close
Workbooks("FILE2.xls").Close

Excel macro: How to extract data from other Excel file [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
excel macro: browse excel file and use its worksheet data
In brief, I want to write a script can do this.
In the current excel file, there is a macro button. The user can click the button to browse files (another Excel). In that browsed Excel, several worksheets will be load to current Excel workbook and the data will be used.
I write like this
Sub Button1_Click() ' choose LOAD path
objFile = Application.GetOpenFilename(fileFilter:="All Files (* . *) , * . * ") ' browse function
... ' following
Call main_function
End Sub
I write the browse function already. but how to write the following part? eg. the certain worksheet's data in objFile will be used in main_function.
While what you want isn't really clear (I'm not confident I understand your question's intent) I will have a crack at this.
Assuming you have the name of the file you'd like to open in objFile, you can go about extracting data from that spreadsheet like this - I just open the selected workbook, then write the name of all of the sheets in it to Column A in whichever sheet was open before the button was pressed.
Opening a new workbook causes it to be brought to the foreground - so if I didn't grab the active sheet before opening a new book, then set it after opening the new one, you'd end up overwriting data in the workbook you just opened.
Sub Button1_Click()
' choose LOAD path
objFile = Application.GetOpenFilename(fileFilter:="All Files (* . *) , * . * ") ' browse function
Set curSheet = ActiveSheet
Set mWorkbook = Workbooks.Open(objFile)
curSheet.Activate
Call someFunction(curSheet, mWorkbook)
End Sub
Sub someFunction(targetSheet, srcWorkbook)
numSheets = srcWorkbook.Sheets.Count
For i = 1 To numSheets
targetSheet.Cells(i, 1) = srcWorkbook.Sheets(i).Name
Next i
End Sub

VBA - Copy as Path

I need help with a coding requirement that I've not previously experienced. I just browsed a similar issue raised here a couple of years ago - VBA to Copy files using complete path and file names listed in Excel Object.
My issue is similar but somewhat simpler than the OP.
I have a number of folders that each contain about 100 small .csv files; for each folder I need to copy the path for each file to an open worksheet. Each folder of .csv files has its own associated workbook.
As one example, the open workbook is F:\SM\M400AD.xlsm and the active worksheet is CSV_List. The folder containing the .csv files is F:\SM\M400AD.
Doing it manually, my sequence is then:
Open folder F:\SM\M400AD
Select all
Copy path
Paste to Range("B11") of worksheet CSV_List
When I do it manually, as described above, I get a list that looks like:
"F:\SM\M400AD\AC1.csv"
"F:\SM\M400AD\AC2.csv"
"F:\SM\M400AD\AE.csv"
"F:\SM\M400AD\AF.csv"
"F:\SM\M400AD\AG.csv"
"F:\SM\M400AD\AH1.csv"
"F:\SM\M400AD\AH2.csv"
"F:\SM\M400AD\AJ.csv"
and on down the page until I have a list of 100 paths. This single column list is then pasted into worksheet CSV_List, starting at Range("B11").
I need to automate this and would be grateful if a VBA guru could kindly code this for me.
Such of question has been asked before, for example:
Loop through files in a folder using VBA?
List files in folder and subfolder with path to .txt file
The difference is you want to "automate" it, which means you want to execute code on workbook Open event.
How to achieve that?
Open F:\SM\M400AD.xlsm file.
Go to Code pane (ALT+F11)
Insert new module and copy below code
Option Explicit
Sub EnumCsVFilesInCurrentFolder()
Dim sPath As String, sFileName As String
Dim i As Integer
sPath = ThisWorkbook.Path & "\"
i = 11
Do
If Len(sFileName) = 0 Then GoTo SkipNext
If LCase(Right(sFileName, 4)) = ".csv" Then
'replcae 1 with proper sheet name!
ThisWorkbook.Worksheets(1).Range("B" & i) = sPath & sFileName
i = i + 1
End If
SkipNext:
sFileName = Dir(sPath)
Loop While sFileName <> ""
End Sub
Now, go to ThisWorkbook module and insert below procedure:
Private Sub Workbook_Open()
EnumCsVFilesInCurrentFolder
End Sub
Save and close workbook
The workbook is ready to use. Whenever you open it, EnumCsVFilesInCurrentFolder macro will be executed.
Note: you have to change above code to restrict the number of records.