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

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

Related

Open and update an existing workbook with 2 worksheets

This may be simplistic to most of you. I just started using VBA to create and update excel workbooks. I found some code on the internet to open and update an existing workbook and worksheet. Like I said, I am brand new at this. Does this code even make sense? I just need to know how to open an existing workbook and all the examples I have found aren't working in our environment.Thanks for any help I can get
Dim wbSource, xlApp, srcWorksheet
'initialize
Set xlApp = CreateObject("Excel.Application")
'open source and target files
Set wbSource = lApp.Workbooks.Open("X:\GCIXCycleCompare_test_auto.xlsx")
set srcWorksheet = wbSource.Worksheets("NewCycle")
srcWorksheet.sheets("NewCycle").Activate
srcWorksheet.Rows("1:1").Delete
If you are in Excel VBA, this isn't quite what you want. This code was written for an external app (say written in VB6) to open Excel remotely and then do stuff to that copy of Excel. If you are already in Excel/VBA you obviously don't need to do that.
In VBA, the equivalent code would be something like this:
Public Sub MyCode()
Dim wb as Workbook
Dim ws as Worksheet
Set wb = Application.Workbooks.Open("X:\GCIXCycleCompare_test_auto.xlsx")
Set ws = wb.Worksheets("NewCycle")
ws.Rows(1).Delete
End Sub
If you run this code (by click F5 from inside VBA ... or by run macro in Excel) it should open up the test file off the X: drive, and then delete the first row of it.

Why are two Excel sheets opening when I try to create one in VBscript?

I have written a program in VBscript to create an excel sheet. The program works fine, and when i click on the Excel sheet to open it, the sheet i created is opened as well as a new excel "Book1". Why is this happening? How can I stop it so that only the sheet i created will open?
Code is given below:
Set objExcel = CreateObject("Excel.Application") 'Bind to the Excel object
objExcel.Workbooks.Add 'Create a new workbook.
Sheet = 1 'Select the first sheet
Set objSheet = objExcel.ActiveWorkbook.Worksheets(Sheet) 'Bind to worksheet.
objSheet.Name = "InfoBook" 'Name the worksheet
strExcelPath = "c:\scripts\InfoBook.xlsx" 'Set the save location
objSheet.Range("A1:C1").Font.Bold = True
objExcel.Columns(3).AutoFit()
objSheet.Cells(1, 1).Value = "Date" 'Row 1 Column 1 (A)
objSheet.Cells(1, 2).Value = "Time" 'Row 1 Column 2 (B)
objSheet.Cells(1, 3).Value = "Category" 'Row 1 Column 3 (C)
objExcel.ActiveWorkbook.SaveAs strExcelPath
objExcel.ActiveWorkbook.Close
objExcel.Application.Quit
Have you tried rebooting your computer and running the code again?
The additional workbook may be left over from an earlier, failed, attempt at running the code. Although I cannot replicate the error using just your posted code, I can replicate it by performing
Set objExcel = CreateObject("Excel.Application") 'Bind to the Excel object
objExcel.Workbooks.Add 'Create a new workbook.
and then running your script.
Because the first script creates a workbook but doesn't close the Excel application, when you open the workbook created by your script, the still running instance of Excel is opened (which still contains Book1) and your workbook is also opened.
Rebooting your computer will get rid of the running instance of Excel - or you can just terminate it using Task Manager.
I figured out what the problem is. The line
objSheet.Name = "InfoBook"
creates a workbook with that name. Then when we specify the path for the workbook, we are again creating a workbook of that name in the following line
strExcelPath = "c:\scripts\InfoBook.xlsx"
so the trick is to only name the excel workbook in the path, so it'll only be opened once, and saved where we want it.
Thanks to everyone who spent time on this little predicament of mine. Hope it helped you guys too.

Copy and paste Excel sheets

Private Sub CommandButton1_Click()
Dim ws As Worksheet
With Application.FileDialog(msoFileDialogFilePicker)
.Show
If .SelectedItems.Count <> 0 Then
fldr = .SelectedItems(1)
End If
End With
Sheets.link.Value = fldr
For i = 1 To Worksheets.Count
Set ws = Worksheets(i)
If ws.Cells(2, 1) = "X" Then
Sheets.ComboBox1.AddItem (ws.Name)
End If
Next i
Workbooks.Open (fldr)
Sheets.Show
End Sub
Private Sub Add_Click()
Dim x As String
Dim ws As Workbook
x = Right(link.Value, (Len(link.Value) - InStrRev(link.Value, "ild") - 3))
Workbooks("Test.xlsm").Activate
Worksheets(ComboBox1.Value).Copy Before:=Workbooks(x).Worksheets("Contract")
End Sub
So the basic idea is, you click a button on an Excel sheet. The user then finds the file they want to copy the sheets to. It will find all of a specific type of sheet, put it in a forms combobox and open the selected Excel file.
Then you choose a sheet from the combobox and copy it from one workbook to the other. It all works until the copying part. I get a long error:
Excel cannot insert the sheets into the destination workbook, because it contains fewer rows and columns that the source workbook. To move or copy the data to the destination workbook, you can select the data and then use Copy and Paste commands to insert it into the sheets of another workbook.
If the destination workbook comes from an older version of Excel (extension .xls for instance, Excel 97 or Excel 2003), the limit of number of rows in old worksheets is 2^16-1, as the row number is encoded on 16 bits. In newer versions, this number is encoded on 32 bits.
Hence, copying a worksheet "as a whole" from a newer version into a workbook from an older version raises this error. From my test, this error occurs even if the actually used range in the copied worksheet is small.
I had this same problem.
Following #A.S.G. suggestion, I saved the old workbook with the new file format (xlsx), closed and reopened it and everything worked fine afterwards.
Hope it helps.

Excel VBA - Can I manipulate data on another workbook?

Background:
Every month I need to run a report. However, before I can do this, I must export some data in to excel. Once the data is in excel, I have to alter some columns and get the format correct before it is appended to the end of another document to do some analysis on.
What I would like:
I would like to have the document that I append the data to open. I will then export the data in to excel from my program (excel just opens with the data and it is not saved anywhere) and from my larger document, run a VBA script that will alter the data on the other workbook (Book1) so that it can be copied over to the analysis document when in the correct format.
What I have so far:
I have started basic. So far all I am trying to do is set all the cells to the correct height to make it easier to read. However, when I run this code, I get:
Run-time error '9':
Subscript out of range
The code I have so far is:
Sub Data_Ready_For_Transfer()
' Format all cell heights to 15
With Workbooks("Book1.xlsm").Worksheets("Sheet1")
Cells.RowHeight = 15
End With
End Sub
It appears to be having issues with the With Workbooks("Book1.xlsm").Worksheets("Sheet1") part of the code. I have also tried With Workbooks("Book1").Worksheets("Sheet1") and I have tried this with the open, unsaved document and a saved version of the workbook.
Am I missing something obvious?
As follow up from comments, workbook Book1 was opened in another instance of Application object.
In that case this code should work (for already opened workbook):
Sub Data_Ready_For_Transfer()
Dim wb As Workbook
Set wb = GetObject("Book1")
'if we get workbook instance then
If Not wb Is Nothing Then
With wb.Worksheets("Sheet1")
.Cells.RowHeight = 15
End With
End If
End Sub
One more issue, I've changed Cells.RowHeight = 15 to .Cells.RowHeight = 15 to specify, that Cells belongs to workbook Book1 sheet Sheet1.

How to open a file in an active workbook? VB.NET 2008

I have a program that filters data and then outputs it to a tabg delimited file. I then use Excel Interop to open this file in Excel because directly outputting to a worksheet takes too long. So currently I am using this code:
AD.DF.WriteToFile(vbTab)
Dim WB As Workbook = ExcelApp.Workbooks.Open(AD.DF.DatafileInfo.WriteToFileLocation)
ExcelApp.Visible = True
The first line takes the filtered data and outputs to a tab delimited file. The second opens that same file in a new workbook in Excel. And obviously the third makes Excel visible. Here is my problem though: right now when this code is run there are two open workbooks. I already have an active workbook and I would just like to open this file to that workbook.
If this is possible, how do I do it?
Thank you.
Look at the GetObject function.
Dim MyXL As Object
MyXL = GetObject(, "Excel.Application")
should get you a reference to the currently running instance of Excel.
In the code I created an object that is an Excel Workbook. I then set the created workbook as the ExcelApp.ActiveWorkbook. Then I was able to open the file without another workbook being created.