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

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

Related

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

Excel VBA - close an active table/document by name only - NOT filepath

i have a workbook where i regularly update stock prices from a yahoo link. it opens up a read only file named 'table'. below is an example link
http://real-chart.finance.yahoo.com/table.csv?s=INTC&a=05&b=9&c=2000&d=06&e=7&f=2016&g=d&ignore=.csv
things get messy when i have multiple 'table' file open that results in several additional clicks to import the data.
is there a way i can have a macro where any csv/xls files open named 'table' can be closed?
the function used to get this data is
=HYPERLINK("http://real-chart.finance.yahoo.com/table.csv?s=INTC&a=05&b=9&c=2000&d=06&e=7&f=2016&g=d&ignore=.csv","link")
and i've used similar close workbook scripts before, but i cannot for the life of me figure out how to reference this open file for it to be closed
This assumes that the files open in the same Excel instance as the one running the code, and also that you don't want to save any changes to the open files.
Sub CloseTableWorkbooks()
Dim wb as Workbook
For each wb in Application.Workbooks
If Instr(1, wb.Name, "table") Then wb.Close False
Next
End Sub
Dim book As Workbook
For Each book In Application.Workbooks
if book.name = "table.xls" or book.name = "table.csv" then
book.close
end if
Next
You'll get some messages like "Do you want to save before you close?" or the like, which Excel normally does. You can prevent them too but I'm not sure if you want that or not.

getting vales from different file locations contained in cells Excel

So I'm trying to create a tracking file in Excel and in cell M5, I have a file location which links to a supporting document and as such, contains some duplicated information so I want to try and pull certain fields (B8 in this example) from the external files referenced in M5.
I have tried =([M5]Sheet1!B8) which works to a degree but this brings up a dialogue box and I have to select the file location manually which is too manual for the purpose.
I have also looked into using the INDIRECT function but can't guarantee that both files will be open at the same time, so would prefer another option if possible.
Any suggestions would be hugely appreciated!!
Here is formula you can use to get individual cell values from a closed workbook.
It is a User Defined Function (UDF) and you call it like this:
=GetClosedCell(A3,B3,C3)
The 1st parameter is the workbook path and name.
The 2nd parameter is the worksheet name.
The 3rd parameter is the address of the cell.
Place this function in a standard code module:
Public Function GetClosedCell(ByVal FileSpec$, ByVal SheetName$, ByVal RangeAddress$)
Const CNX = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=[];Extended Properties=""Excel 12.0;imex=1;hdr=no;"""
Const QRY = "SELECT * FROM [.$|:|]"
On Error GoTo errorh
RangeAddress = Range(RangeAddress)(1, 1).Address(0, 0)
With CreateObject("adodb.recordset")
.Open Replace(Replace(QRY, "|", RangeAddress), ".", SheetName), Replace(CNX, "[]", FileSpec)
GetClosedCell = .Fields(0)
End With
Exit Function
errorh:
GetClosedCell = "ERROR: " & Err & " " & Err.Description
End Function
Here is how it would look on a worksheet:
It is possible to grab data from an external file without opening it. For Excel to get a data item, it needs to know:
the file location
the name of the file within that location
the name of the worksheet within that file
the address of the cell within that worksheet
We enter the required info into some cell, say cell C3 in a very specific format:
'C:\TestFolder\[ABC.xls]xxx'!R9C2
note the single quotes!
then running this short macro:
Public Sub GrabData()
Dim r1 As Range, r2 As Range
Set r1 = Range("C3")
Set r2 = Range("C4")
r2.Value = ExecuteExcel4Macro(r1.Value)
End Sub
will retrieve the data and place it in cell C4
Macros are very easy to install and use:
ALT-F11 brings up the VBE window
ALT-I
ALT-M opens a fresh module
paste the stuff in and close the VBE window
If you save the workbook, the macro will be saved with it.
If you are using a version of Excel later then 2003, you must save
the file as .xlsm rather than .xlsx
To remove the macro:
bring up the VBE window as above
clear the code out
close the VBE window
To use the macro from Excel:
ALT-F8
Select the macro
Touch RUN
To learn more about macros in general, see:
http://www.mvps.org/dmcritchie/excel/getstarted.htm
and
http://msdn.microsoft.com/en-us/library/ee814735(v=office.14).aspx
Macros must be enabled for this to work!

Extracting certain cells from excel files in a specified directory

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

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.