Using VBA to read/write data from Excel files

How would I go about using Visual Basic to extract
data from cells of any given Excel file and store that
data in variables of my running VBA program??
Similary, how would I write back a value into
that same file into a specified cell??

I just need some basic examples regarding which
functions to use for file operations to get me going.

Thank you all!


0
Robert
11/23/2009 7:19:38 AM
excel.programming 6508 articles. 2 followers. Follow

5 Replies
24081 Views

Similar Articles

[PageSpeed] 37

I have been trying the following code in my VBA module(s):

Dim x As Integer

x = Workbooks("My File").Worksheets("Sheet1").Range("D8").Value

However, I get the following error message:

"Run time error 9 - Subscript out of range"

What am I doing wrong??



"Robert Crandal" <nobody@gmail.com> wrote in message 
news:JQqOm.47432$W77.4677@newsfe11.iad...
> How would I go about using Visual Basic to extract
> data from cells of any given Excel file and store that
> data in variables of my running VBA program??
> Similary, how would I write back a value into
> that same file into a specified cell??
>
> I just need some basic examples regarding which
> functions to use for file operations to get me going.
>
> Thank you all!
>
> 

-1
Robert
11/23/2009 9:03:41 AM
So, just to re-phrase my original question, I want to be able to read
the cell values of a closed "xls" file using Visual Basic AND without
opening the source workbook on my screen.

After searching the Internet, I discovered that I have to use an
automation object to open the workbook and retrieve the value of
cell.  Here is some sample code that I found:

----------------------------------------------------
Dim oXL As Excel.Application, oBook As Excel.Workbook, oSheet As 
Excel.Worksheet, vValue As Variant

Set oXL = New Excel.Application
Set oBook = oXL.Workbooks.Open("D:\Test.xls")
Set oSheet = oBook.Worksheets("Sheet1")

vValue = oSheet.Cells(1, 1).Value       'Get the value from cell A1
Debug.Print vValue

Set oSheet = Nothing
oBook.Close
Set oBook = Nothing
oXL.Quit
Set oXL = Nothing
----------------------------------------------------

This code actually works, the problem is that it is sooooo extremely slow
(in my opinion) just to read the value of Cells(1,1).

Does anybody know of any quicker ways to use VBA to read data
from closed Excel files??

Thank you everyone!

0
Robert
11/23/2009 10:43:20 AM
You could add formulas to empty cells to retrieve values from your sending
workbook.

=======

John Walkenbach has a routine that can get values from a closed workbook:
http://j-walk.com/ss/excel/eee/eee009.txt
Look for either:  GetDataFromClosedFile or GetValue.

=======

As for updating those cells, I'd open the workbooks, update the cells and close
the workbook.  The biggest delay I've seen is when my receiving file is on a
network.  

I'll sometimes copy those receiving files to my harddrive, run my macro and then
copy those updated files back to the network.

Robert Crandal wrote:
> 
> So, just to re-phrase my original question, I want to be able to read
> the cell values of a closed "xls" file using Visual Basic AND without
> opening the source workbook on my screen.
> 
> After searching the Internet, I discovered that I have to use an
> automation object to open the workbook and retrieve the value of
> cell.  Here is some sample code that I found:
> 
> ----------------------------------------------------
> Dim oXL As Excel.Application, oBook As Excel.Workbook, oSheet As
> Excel.Worksheet, vValue As Variant
> 
> Set oXL = New Excel.Application
> Set oBook = oXL.Workbooks.Open("D:\Test.xls")
> Set oSheet = oBook.Worksheets("Sheet1")
> 
> vValue = oSheet.Cells(1, 1).Value       'Get the value from cell A1
> Debug.Print vValue
> 
> Set oSheet = Nothing
> oBook.Close
> Set oBook = Nothing
> oXL.Quit
> Set oXL = Nothing
> ----------------------------------------------------
> 
> This code actually works, the problem is that it is sooooo extremely slow
> (in my opinion) just to read the value of Cells(1,1).
> 
> Does anybody know of any quicker ways to use VBA to read data
> from closed Excel files??
> 
> Thank you everyone!

-- 

Dave Peterson
1
Dave
11/23/2009 1:48:44 PM
Can you give an example of adding "formulas to empty cells to retrieve 
values from
your sending workbook"???

Additionally, I discovered that the GetValue() function mentioned below DOES
work very well for reading individual cells.  However, if I want to read a 
range
of cells (say "A1:L25") then my code starts to look ugly.  It is also a very
slow process of reading a range of cells one cell at a time by calling
GetValue() for each individual cell.  Can GetValue somehow be used to
read a range of cells in a faster manner???

As for the GetDataFromClosedFile() function, it seems to be missing function
parameters, so I have no clue how to use that one.

Hope to hear from you soon!  Thank you!


"Dave Peterson" <petersod@verizonXSPAM.net> wrote in message 
news:4B0A92BC.7E2C0753@verizonXSPAM.net...
>
> You could add formulas to empty cells to retrieve values from your sending
> workbook.
>
> =======
>
> John Walkenbach has a routine that can get values from a closed workbook:
> http://j-walk.com/ss/excel/eee/eee009.txt
> Look for either:  GetDataFromClosedFile or GetValue.
>
> =======

0
Robert
11/25/2009 10:16:06 AM
Create a new worksheet in the receiving workbook.
Open your sending file.
Select the cell in the sending worksheet in the sending workbook.
Edit|Copy (or ctrl-c)

Back to A1 of that new worksheet in the receiving workbook.
Edit|paste special|paste link

Close the sending workbook.

Now back to the receiving workbook.

Start recording a macro.
Select A1 of that new sheet
Hit F2 (to edit the cell)
Hit Enter (don't make any changes)
Stop recording the macro.

Your recorded macro will have the syntax building that formula.  Depending on
the names of the paths/folders/workbooks/worksheets and addresses, you'll want
to match that syntax when you build the formula using variables.

If you have trouble, share the exact recorded formula and your variable names
and what they represent.

Robert Crandal wrote:
> 
> Can you give an example of adding "formulas to empty cells to retrieve
> values from
> your sending workbook"???
> 
> Additionally, I discovered that the GetValue() function mentioned below DOES
> work very well for reading individual cells.  However, if I want to read a
> range
> of cells (say "A1:L25") then my code starts to look ugly.  It is also a very
> slow process of reading a range of cells one cell at a time by calling
> GetValue() for each individual cell.  Can GetValue somehow be used to
> read a range of cells in a faster manner???
> 
> As for the GetDataFromClosedFile() function, it seems to be missing function
> parameters, so I have no clue how to use that one.
> 
> Hope to hear from you soon!  Thank you!
> 
> "Dave Peterson" <petersod@verizonXSPAM.net> wrote in message
> news:4B0A92BC.7E2C0753@verizonXSPAM.net...
> >
> > You could add formulas to empty cells to retrieve values from your sending
> > workbook.
> >
> > =======
> >
> > John Walkenbach has a routine that can get values from a closed workbook:
> > http://j-walk.com/ss/excel/eee/eee009.txt
> > Look for either:  GetDataFromClosedFile or GetValue.
> >
> > =======

-- 

Dave Peterson
0
Dave
11/25/2009 2:14:51 PM
Reply:

Similar Artilces:

HELP WITH VBA
I am trying to finish writing some simple program. My problem is that when I try and change the arguement from SELECTION CHANGE to CHANGE, it doesn't work. Can someone help? Private Sub Worksheet_Change(ByVal Target As Range) If Worksheets("Sheet3").Range("B3").Value = 2 Then Worksheets("Sheet1").Range("F3") = Worksheets("Sheet3").Range("F4").Value End Sub My second problem is that I would like my data rather than appearing in a cell, appear in a TEXT BOX. What do I do? Copying your exact same post from 3 days ago word...

Line charts using temperature and time factors
I want to create a line chart showing comparisons of heating and time. For example one item is held @ 30deg for 10secs then 100degs for 30secs while the comparison is plotted to show the difference. Help appreciated. try x-y scatter chart data-columnwise. Excelon_Ls <Excelon_Ls@discussions.microsoft.com> wrote in message news:6B9F5547-A35C-4272-9FDC-F2CE6122D783@microsoft.com... > I want to create a line chart showing comparisons of heating and time. For > example one item is held @ 30deg for 10secs then 100degs for 30secs while the > comparison is plotted to show the diff...

READ ONLY ERROR 03-15-07
Hello, Does anyone know how I can fix this.....It means that the control is set to read only (Enabled = No); that theForm is read only (Allow Edits = No); or that the subform is based ona Query which is not updateable.I have a subform on my main form and when i go to select a drop down from that subform...the read only error comes up....the information is stored, however the error still comes up????helpRW If you open the main form with Allow Edits set to No, the subform will be locked.The subform also as its own AllowEdits property.Also make sure the subform's RecordSourceType property is ...

Excel slow to open a book, but fast empty
Cheers! My Excel 2002 has been working fine, but lately has got a problem: it is very, very slow when opening an xls file by clicking it. It is fast as it should when I open it empty from the start menu. If I create the simplest possible book by just typing something in one cell and saving it, opening it is still slow. Perhaps this format is easier: 0. Excel has been working as it should. 1. Fast when running from start menu, opening an empty book. 2. Slow when clicking an xls file, independent of book complexity. Excel comes up with a transparent main window, but with everything else visi...

Outlook using imap is receiving but not sending
Messages are being put in Sent folder and Send/Receive shows no errors but emails are not actually getting sent. This is a new install of Outlook on a new computer. Have I messed up the setup? "Theatre Girl" wrote in message news:64BB711F-FE56-440C-A850-DADCA8C3BA00@microsoft.com... > Messages are being put in Sent folder and Send/Receive shows no > errors but > emails are not actually getting sent. This is a new install of > Outlook on a > new computer. Have I messed up the setup? IMAP is not a sending protocol. It is used for receiving mails (out of your ...

VBA: move to the next cell down from anywhere in the sheet
I am deleting rows based on a value in a column (< 16) and if the valu is 16 or greater I want to move down to the next row and check tha value and so on. i am using a Do Until value = "". What is the code for moving down to the next cell below ActiveCell -- jm ----------------------------------------------------------------------- jmp's Profile: http://www.excelforum.com/member.php?action=getinfo&userid=2903 View this thread: http://www.excelforum.com/showthread.php?threadid=48770 Activecell.Offset(1,0).Select I would not recommend this though. If you want to dele...

HOW TO USE HYPERLINK within a droplist?
I have a question aabout this: eg. I set row A with validation list "yes/no", i want that if choose "yes", then open a word document named "checklist.doc". Instead of using a validation list, you could use a "yes" button and a "no" button. The yes button can be linked to a macro to open the word document. The no button can be linked to a macro the will type the text "Go to next step" or something like that. "Bonny" wrote: > I have a question aabout this: > eg. > I set row A with validation list "yes...

Is there a way to export and save file properties for an Excel do.
Can this be done either in text or XML? ...

XmlTextReader and 2GB file limit
Are there any work arounds to get XmlTextReader to work with files bigger than 2GB? I tried to get the source of XmlTextReader and create a version with long (instead of int) offsets but I can't compile it due to package restrictions. Best wishes, Hugh McFadden hugh.mcfadden@visiongain.com Hugh McFadden wrote: > Are there any work arounds to get XmlTextReader to work with files bigger > than 2GB? I tried to get the source of XmlTextReader and create a version > with long (instead of int) offsets but I can't compile it due to package > restrictions. Sorry for lame qu...

using forms
Vista Home Premium 32 / Outlook 2007 I have created some forms that used to work. No more. On selecting a form, I get "The form required to view this message cannot be displayed. Contact the administrator. To my knowledge, I am the administrator. This is a stand-alone PC in my residence. If I go to Manage User Accounts, it shows only 2 accounts - LastName Administrator and Guest. I have googled my problem and found references to FRMCACHE.DAT which I am told to delete and restart Outlook. Did that. Opened Outlook and tried to open a form. Same error. And FRMCACHE.DAT was not ...

Using Spanish on Publisher
I have copied and pasted a document in Spanish from Word to Publisher. Prompts keep coming up telling me that it cannot "hyphenate" this document. I'm guessing that it means since it's in another language it needs something to be able to spell-check, etc. I really don't care about checking the spelling, but the pop-ups keep interferring with my arranging the flyer I desperately need to get completed. It tells me to put in the disk and download the "hyphenate" feature. Can I download this from the net since I have no disks. Publisher came with my n...

Excel Display Errors in file
I have several excell 2000 documents that when opened, the first sheet in the workbook will display most of the data at around a size 72 font that will not show in the cell. All the other sheets in this workbook are fine. This also effects the column and row headings (A B C, 1 2 3). If I go to View > Zoom and zoom from the default of 75% to anything else, it fixes the problem. I can then zoom back to 75% and everything still looks fine. (Including row and column headings) The next time I open the file, the first sheet is still messed up. I have tried saving to web page and...

Read receipts #3
Exchange 5.5 Two questions. When a message is received through the IMC and the external user has requested a read receipt, is a read receipt sent out to them? If so, how can I stop read receipts being sent to external clients only? Any help appreciated. Mike. If I recall, this enabled or disabled on the IMC itself. -- John Oliver, Jr. MCSE, MCT, CCNA, Exchange MVP Microsoft Certified Partner "Mike" <anonymous@discussions.microsoft.com> wrote in message news:1f50a01c457a7$faba8820$a501280a@phx.gbl... > Exchange 5.5 > Two questions. > When a message is received ...

I used Omsgclas.exe Utility and my contacts don't use then new form
I created a new form for contacts. I followed the three steps in the document How to Update Existing Items to Use a New Custom Form. I can click on Action and do new contact and the new form is used. I used Omsgclas.exe utility to change the message class of the contacts. It shows as changed. However, when I click on an old contact (previous to changing the form), A message form comes up (not the old contact form and not my new contact form). Anyone have any help how to get my new form pulled up for old messages? Note: I had a form with a ' in the name, I made a new form w...

topographical data maps in excel
I have seen this done, and would like to know how to create topgraphical maps of data sets using excel. I want to take a sample of data ponts and plot the points (easy), than color the plot based upon the values of the points You seem to have been neglected by our community. Yes, it can be done, if I understand your intention correctly. The topography in your approach means, in a sense, the 3D chart. The first two of the three values defininig each point specify the x- and y-coordinates (like on a map); the third value is represented by prescribed colors or shades. You must have you...

FormulaR1C1 using variables
I want to do this but can't: ActiveCell.FormulaR1C1 = "=MyFunction(R[variable]C[variable])" What are my options? Try something like ActiveCell.FormulaR1C1 = _ "=MyFunction(R" & CStr(variable) & "C" & CStr(variable) & ")" Cordially, Chip Pearson Microsoft Most Valuable Professional, Excel, 1998 - 2010 Pearson Software Consulting, LLC www.cpearson.com On Wed, 21 Apr 2010 13:52:01 -0700, Cheah <Cheah@discussions.microsoft.com> wrote: >I want to do this but can't: > >ActiveCell.Fo...

Using lookup formula using more than one cell
I have a spreadsheet which lists clients by first name, last name, postcode and phone number - all in separate columns e.g. Andy Roberts M56 7HN 0161 428 3856 I have these all in one worksheets and in a named range called "Clients" On a separate worksheet (within the same workbook) I log all my enquiries. What I want to be able to do is type in to a cell the first name then in the next cell the last name and the following cells get populated with postcode and phone number based on BOTH of the first two cells by looking up the "Clients" range. I can get it...

Snapshot Viewer will not open .snp file
We have a client that sends us .snp files as email attachments. We have Office 2007 installed on new Windows XP PCs. We have the Snapshot Viewer installed. When we attempt to open an .snp file, either from email or after saving attachment to the desktop, all we get is a blank Snapshot Viewer window. If we re-install the Shapshot Viewer we can then open one .snp file and then it reverts back to opening with a blank viewer window for subsequent ..snp files that are opened. Any ideas would be greatly appreciated Susie Install a different Printer Driver for the workstations exhibiting ...

Display As = File as & (address in parens)
I just moved all my contacts into a new .pst file (I'm using OL 2003) and something changed. I USED TO have "Display As" show only the person's name, and not the person's name PLUS the email address in parens as the default does. In other words, default would show "JOHN SMITH (johnsmith@aol.com)". But when I created all those entries, I changed them to show only "JOHN SMITH". In my new file, Outlook has changed all my "Display As" entries to the default: name AND email address. It's not how I want it, so I'm hoping there'...

In Excel, how do I insert User Name (author) in a cell.
The function =CELL("filename",A1) returns a file name and sheet name in a cell. How can I obtain the User Name? You can write some VBA to do it. Sub Return_UserName() Sheets("sheet1").Range("A2").Value = Application.UserName End Sub -- Excel_Geek ------------------------------------------------------------------------ Excel_Geek's Profile: http://www.excelforum.com/member.php?action=getinfo&userid=26423 View this thread: http://www.excelforum.com/showthread.php?threadid=398347 And to return just the filename (if you like) you can use this for...

Using XML with ASP.NET
I want to know where can I find Tutorials/Articles to learn implementing XML with asp.net. I am working on ASP.NET using C# from last one month. I have idea about XML but had not implemented yet with ASP.NET. Thanks in advance. Thanks Vinod Jajoo ...

Importing Excel data into Access?
Can Excel data be imported into Access easily!? I know from Word table I can simply copy and paste but it is not that easy when doing from Excel to Access! I downloaded this manual from http://www.mousetraining.co.uk/training-manuals/Access2003Intro.pdf but couldn't find this topic If anyone knows please let me know! Cheers Raj Hello, there are plenty of sources. e.g.: http://office.microsoft.com/training/training.aspx?AssetID=RC102722321033 Stefan. "Rajeev Rawat" wrote: > Can Excel data be imported into Access easily!? I know from Word table &g...

Compile error using CTypedPtrList
Hi, I am having problems at compile time using the following line: CTypedPtrList<CPtrList, CString*> m_ClientList ; When compiled I get the following errors: emailcfgdlg.h(114) : error C2143: syntax error : missing ';' before '<' emailcfgdlg.h(114) : error C2501: 'CTypedPtrList' : missing storage-class or type specifiers emailcfgdlg.h(114) : error C2059: syntax error : '<' emailcfgdlg.h(114) : error C2238: unexpected token(s) preceding ';' I am using the version 6 of the compiler with SP5. Now I think this is something to do with the c...

How do I import Excel into Microsoft Money
#1 - This question is more likely to get an answer in the Money newsgroup than here #2 - Place your question in the body of the message, with a little more explanation of what you want to accomplish "Tax Help" wrote: > You can't do it directly. The only formats that Money can import are QIF and OFX. Go to Google and search for excel money import qif to get multiple hits including macros and/or commercial solutions. One the I found is http://www.bigredconsulting.com/AboutXLQIFConverter.htm Their program is $39. On Mon, 21 Mar 2005 12:55:03 -0800, "Tax H...

Using secured OMA
Hi, Please help me with my misunderstanding. When I try ro connect by t68i or z600 (WAP 2.0) to OMA directly with SSL required, using mydomain.com/oma, of course, I get 403 error. When I use https://mydomain.com/oma I get "Couldn't reach the indicated web server." altough it works fine with Pocket PC. What's wrong? What should I configure to establish secured connection from mobile phone? Best regards, Vit Knyshevich. "Vit Knyshevich" <abuse_vit_knysh@hotmail.com> wrote: >Please help me with my misunderstanding. When I try ro connect by t68i or >z60...