Write data from Access to Excel file - vba

I am trying to use the following code to write data into an excel file
Dim objexcel As Excel.Application
Dim wbexcel As Excel.Workbook
Dim wbExists As Boolean
Set objexcel = CreateObject("excel.Application")
objexcel.Visible = True
On Error GoTo Openwb
wbExists = False
Set wbexcel = objexcel.Documents.Open("C:\Documents and Settings\TAYYAPP\Desktop\test folder\ERROR REPORT2.xls")
wbExists = True
Openwb:
On Error GoTo 0
If Not wbExists Then
Set wbexcel = objexcel.Workbook.Add
End If
but I'm getting an
runtime error object doesn't support property or method
in the line
Set wbexcel = objexcel.Workbook.Add
I have referenced the Excel object library.

You will need to change this line:
Set wbexcel = objexcel.WorkBooks.Open( _
"C:\Documents and Settings\TAYYAPP\Desktop\test folder\ERROR REPORT2.xls")
Note WorkBooks, not Documents
As For this line Set wbexcel = objexcel.Workbook.Add, wbexcel is defined as a workbook, but the line is an action, so:
objexcel.Workbooks.Add
Set wbexcel = objexcel.ActiveWorkbook
EDIT:
As an aside, DoCmd.Transferspreadsheet is probably the easiest way of transferring a set of data (query, table) from Access to Excel.

I have got this code which works fine
Dim objexcel As Excel.Application
Dim wbexcel As Excel.Workbook
Dim wbExists As Boolean
Dim objSht As Excel.Worksheet
Dim objRange As Excel.Range
Set objexcel = CreateObject("excel.Application")
objexcel.Visible = True
On Error GoTo Openwb
wbExists = False
Set wbexcel = objexcel.Workbooks.Open("C:\Documents and Settings\TAYYAPP\Desktop\test folder\reports\ERROR REPORT2.xls")
Set objSht = wbexcel.Worksheets("Sheet1")
objSht.Activate
wbExists = True
Openwb:
On Error GoTo 0
If Not wbExists Then
objexcel.Workbooks.Add
Set wbexcel = objexcel.ActiveWorkbook
Set objSht = wbexcel.Worksheets("Sheet1")
End If
but I want to add one more check that if the file exists then I want to see if its is populated with values and if so then I want the next set of values to be populated from the end. As of now it is overwriting the existing values

Related

Output Worksheet Names into a table in ACCESS VBA

I have the below code to get all the Sheetnames of a selected workbook. How do I get all the names of the sheets and import them into a table in the Access Database?
Public Sub PickSheets1(fileName As String)
Dim objExc As Object
Dim objWbk As Object
Dim objWsh As Object
SQLInsert = "INSERT INTO Sheets Table (Sheets) Values (objWbk.Worksheets.Name)"
Set TabInsert = CurrentDb.CreateTableDef("Sheets Table")
Set TabFields = TabInsert.CreateField("Sheets")
Set objExc = CreateObject("Excel.Application")
Set objWbk = objExc.Workbooks.Open(fileName)
Set objWsh = objWbk.Worksheets.Name
DoCmd.RunSQL SQLInsert
'For Each objWsh In objWbk.Worksheets
'TabFields("Sheets").Value objWsh.Name
Set objWsh = Nothing
objWbk.Close
Set objWbk = Nothing
objExc.Quit
Set objExc = Nothing
End Sub
So from within MSAccess you can run this code. Its uses DAO to add the sheet name to the table. Assumes that the table 'Sheets Table' with column 'SheetName' already exists.
call loadSheetNames("C:Path\Workbook.xlsx")
Function loadSheetNames(pstrWB As String)
' Access
Dim db As DAO.Database
Dim rst As DAO.Recordset
' Excel
Dim xl As Excel.Application
Dim xlWB As Excel.Workbook
Dim xlWS As Excel.Worksheet
Set db = CurrentDb
Set rst = db.OpenRecordset("Sheets Table")
Set xl = CreateObject("Excel.Application")
Set xlWB = xl.Workbooks.Open(pstrWB)
For Each xlWS In xlWB.Sheets
Debug.Print xlWS.NAME
rst.AddNew
rst("SheetName") = xlWS.NAME
rst.update
Next
Set rst = Nothing
Set db = Nothing
Set xlWS = Nothing
Set xlWB = Nothing
Set xl = Nothing
End Function
If you want to run the code from within Excel, I can give you that as well.

MS Access - VBA - create new Excel workbook

i use the following VBA-function to read an Excel-file and "create" a new workbook to save this as CSV-file.
This works fine when i run this function for the first time.
Will i run this again it will not open a new workbook (no Errors returned) and i have to close MS Access and then i call this function again.
Has somebody an idea what i'm doing wrong?
public function fctImportExcel ()
Dim objExcel As Excel.Application
Dim wbExcel As Excel.Workbook
Dim wbCSV As Excel.Workbook
Dim wsExcel As Excel.Worksheet
Dim wsCSV As Excel.Worksheet
Set objExcel = New Excel.Application
Set wbExcel = objExcel.Workbooks.Open("filepath")
Set wsExcel = wbExcel.Sheets("sheet1")
objExcel.Visible = True
objExcel.DisplayAlerts = False
wsExcel.Range(wsExcel.Cells(i, 7), wsExcel.Cells(i, 25).End(xlDown)).Copy
Set wbCSV = Workbooks.Add
Set wsCSV = wbCSV.Sheets("sheet")
wsCSV.Range("A1").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
objExcel.CutCopyMode = False
wbCSV.SaveAs FileName:="workbook.csv", FileFormat:=xlCSV, CreateBackup:=False
wbCSV.Close acSaveNo
Set wsCSV = Nothing
Set wbCSV = Nothing
objExcel.DisplayAlerts = True
wbExcel.Close acSaveNo
objExcel.CutCopyMode = False
objExcel.Quit
Set wsExcel = Nothing
Set wbExcel = Nothing
Set objExcel = Nothing
End Function
You always must be extremely specific with Excel objects. So try:
Set wbCSV = objExcel.Workbooks.Add
and careful to close in reverse order:
wbCSV.Close acSaveNo
Set wsCSV = Nothing
Set wbCSV = Nothing
wbExcel.Close acSaveNo
Set wsExcel = Nothing
Set wbExcel = Nothing
objExcel.DisplayAlerts = True
objExcel.CutCopyMode = False
objExcel.Quit
Set objExcel = Nothing

how to copy and paste excel to word with word vba

I want to insert the Excel file at the seartain BOOkmark in the Word doc without opening Excel, automatically inserted when the Word doc opens.
1.I'm thinking to make a pop up window with a open file dialog bottom firstly. And my code is following:(but it only work in excel VBA doesn't work in word VBA how should I change the code so that I can do it in word??? )
Sub openfile()
Dim intChoice As Integer
Dim strPath As String
Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = False
intChoice = Application.FileDialog(msoFileDialogOpen).Show
If intChoice <> 0 Then
strPath = Application.FileDialog( _
msoFileDialogOpen).SelectedItems(1)
End If
End Sub
Then I made a copy and paste bottom the code is as follows:(It also only work when l code it in excel how to change to word vba?)
Sub CopyWorksheetsToWord()
Dim wdApp As Word.Application, wdDoc As Word.Document, ws As Worksheet
Application.ScreenUpdating = False
Application.StatusBar = "Creating new document..."
Set wdApp = New Word.Application
Set wdDoc = wdApp.Documents.Add
For Each ws In ActiveWorkbook.Worksheets
ws.UsedRange.Copy
wdDoc.Paragraphs(wdDoc.Paragraphs.Count).Range.InsertParagraphAfter
wdDoc.Paragraphs(wdDoc.Paragraphs.Count).Range.Paste
Application.CutCopyMode = False
wdDoc.Paragraphs(wdDoc.Paragraphs.Count).Range.InsertParagraphAfter
If Not ws.Name = Worksheets(Worksheets.Count).Name Then
With wdDoc.Paragraphs(wdDoc.Paragraphs.Count).Range
.InsertParagraphBefore
.Collapse Direction:=wdCollapseEnd
.InsertBreak Type:=wdPageBreak
End With
End If
Next ws
Set ws = Nothing
Application.StatusBar = "Cleaning up..."
With wdApp.ActiveWindow
If .View.SplitSpecial = wdPaneNone Then
.ActivePane.View.Type = wdNormalView
Else
.View.Type = wdNormalView
End If
End With
Set wdDoc = Nothing
wdApp.Visible = True
Set wdApp = Nothing
Application.StatusBar = False
End Sub
This should get you started. Place the code below in your Word document in the 'ThisDocument' module.
Add Excel reference to your Word VBA. In the VBA editor go to Tools and then References. Check the box next to Microsoft Excel 14.0 Object Library.
Private Sub Document_Open()
Dim intChoice As Integer
Dim strPath As String
Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = False
intChoice = Application.FileDialog(msoFileDialogOpen).Show
If intChoice <> 0 Then
strPath = Application.FileDialog(msoFileDialogOpen).SelectedItems(1)
End If
CopyWorksheetsToWord (strPath)
End Sub
Function CopyWorksheetsToWord(filePath As String)
Dim exApp As Excel.Application
Dim exWbk As Excel.Workbook
Dim exWks As Excel.Worksheet
Dim wdDoc As Word.Document
Application.ScreenUpdating = False
Application.StatusBar = "Creating new document..."
Set wdDoc = ActiveDocument
Set exApp = New Excel.Application
exApp.Visible = False
Set exWbk = exApp.Workbooks.Open(filePath)
For Each exWks In exWbk.Worksheets
exWks.UsedRange.Copy
wdDoc.Paragraphs(wdDoc.Paragraphs.Count).Range.InsertParagraphAfter
wdDoc.Paragraphs(wdDoc.Paragraphs.Count).Range.Paste
exApp.CutCopyMode = False
wdDoc.Paragraphs(wdDoc.Paragraphs.Count).Range.InsertParagraphAfter
If Not exWks.Name = exWbk.Worksheets(exWbk.Worksheets.Count).Name Then
With wdDoc.Paragraphs(wdDoc.Paragraphs.Count).Range
.InsertParagraphBefore
.Collapse Direction:=wdCollapseEnd
.InsertBreak Type:=wdPageBreak
End With
End If
Next exWks
Application.StatusBar = "Cleaning up..."
Set exWks = Nothing
exWbk.Close
Set exWbk = Nothing
Set exApp = Nothing
Application.StatusBar = False
Application.ScreenUpdating = True
End Function
Save file as macro-enabled file (.docm)
Close word file
Open word file and the code will run. First thing you'll see is a file open box to select the Excel file.
Tested code but there is no error checking.
Update per comment
Bookmarks can be located by name using the following syntax: wdDoc.Bookmarks("Bookmark2").Range
In this case I inserted a bookmark and labeled it Bookmark2
Updated Function Code:
Function CopyWorksheetsToWord(filePath As String)
Dim exApp As Excel.Application
Dim exWbk As Excel.Workbook
Dim exWks As Excel.Worksheet
Dim wdDoc As Word.Document
Dim bmRange As Range
Application.ScreenUpdating = False
Application.StatusBar = "Creating new document..."
Set wdDoc = ActiveDocument
Set exApp = New Excel.Application
exApp.Visible = False
Set exWbk = exApp.Workbooks.Open(filePath)
For Each exWks In exWbk.Worksheets
exWks.UsedRange.Copy
Set bmRange = wdDoc.Bookmarks("Bookmark2").Range
bmRange.Paste
exApp.CutCopyMode = False
wdDoc.Paragraphs(wdDoc.Paragraphs.Count).Range.InsertParagraphAfter
If Not exWks.Name = exWbk.Worksheets(exWbk.Worksheets.Count).Name Then
With wdDoc.Paragraphs(wdDoc.Paragraphs.Count).Range
.InsertParagraphBefore
.Collapse Direction:=wdCollapseEnd
.InsertBreak Type:=wdPageBreak
End With
End If
Next exWks
Application.StatusBar = "Cleaning up..."
Set exWks = Nothing
exWbk.Close
Set exWbk = Nothing
Set exApp = Nothing
Application.StatusBar = False
Application.ScreenUpdating = True
End Function
Since your looping through sheets you'll probably need to play with formatting and how your stacking each section in the document but this should get you going.

Trying to copy data from several ranges in Excel to MS Word

I'm playing around with this code snippet, which I found on SO.
Sub Test()
Dim objWord As Object
Dim ws As Worksheet
Set ws1 = ThisWorkbook.Sheets("Contact Information1")
Set ws2 = ThisWorkbook.Sheets("Contact Information2")
'Set ws3 = ThisWorkbook.Sheets("Contact Information3")
Set objWord = CreateObject("Word.Application")
objWord.Visible = True
objWord.Documents.Open "C:\Users\rshuell001\Desktop\Final Report.docx" ' change as required
With objWord.ActiveDocument
.Bookmarks("BkMark1").Range.Text = ws1.Range("A1:F24").Value
.Bookmarks("BkMark2").Range.Text = ws2.Range("A1:F8").Value
'.Bookmarks("Report3").Range.Text = ws3.Range("A1:F80").Value
End With
Set objWord = Nothing
End Sub
When I look at it, it makes sense. When I run the script, I get an error on this line:
.Bookmarks("BkMark1").Range.Text = ws1.Range("A1:F24").Value
The error message is:
Run-type error 13
Type mismatch
1) I'm not sure '.Bookmarks("BkMark1").Range.Text' will do what I want. I think it's more of a standard copy/paste.
2) I want to make sure the table fits in the Word document, so I'm going to need something like the line below, to get it to do what I want.
wd.Tables(1).AutoFitBehavior wdAutoFitWindow
Any ideas on how to make this work?
Thanks!
I came up with the script below. It does what I want.
Sub Export_Table_Word()
'Name of the existing Word doc.
'Const stWordReport As String = "Final Report.docx"
'Word objects.
Dim WDApp As Word.Application
Dim WDDoc As Word.Document
Dim wdbmRange1 As Word.Range
'Excel objects.
Dim wbBook As Workbook
Dim wsSheet1 As Worksheet
Dim rnReport1 As Range
'Initialize the Excel objects.
Set wbBook = ThisWorkbook
Set WDApp = New Word.Application
'Set wdDoc = wdApp.Documents.Open(wbBook.Path & "\" & stWordReport)
Set WDDoc = WDApp.Documents.Open("C:\Users\rshuell001\Desktop\Final Report.docx")
'Delete old fields and prepare to replace with new
Dim doc As Document
Dim fld As Field
Set doc = WDDoc
For Each fld In doc.Fields
fld.Select
If fld.Type = 88 Then
fld.Delete
End If
Next
Set wsSheet = wbBook.Worksheets("Contact Information1")
Set rnReport = wsSheet.Range("BkMark1")
Set wdbmRange = WDDoc.Bookmarks("BkMark1").Range
'Turn off screen updating.
Application.ScreenUpdating = False
'Copy the report to the clipboard.
rnReport.Copy
'Select the range defined by the "Report" bookmark and paste in the report from clipboard.
With wdbmRange
.Select
.Paste
End With
WDDoc.Tables(1).AutoFitBehavior wdAutoFitWindow
Set wsSheet = wbBook.Worksheets("Contact Information2")
Set rnReport = wsSheet.Range("BkMark2")
Set wdbmRange = WDDoc.Bookmarks("BkMark2").Range
Application.ScreenUpdating = False
rnReport.Copy
With wdbmRange
.Select
.Paste
End With
WDDoc.Tables(2).AutoFitBehavior wdAutoFitWindow
Set wsSheet = wbBook.Worksheets("Contact Information3")
Set rnReport = wsSheet.Range("BkMark3")
Set wdbmRange = WDDoc.Bookmarks("BkMark3").Range
Application.ScreenUpdating = False
rnReport.Copy
With wdbmRange
.Select
.Paste
End With
WDDoc.Tables(3).AutoFitBehavior wdAutoFitWindow
'Save and close the Word doc.
With WDDoc
.Save
.Close
End With
'Quit Word.
WDApp.Quit
'Null out your variables.
Set fld = Nothing
Set doc = Nothing
Set wdbmRange = Nothing
Set WDDoc = Nothing
Set WDApp = Nothing
'Clear out the clipboard, and turn screen updating back on.
With Application
.CutCopyMode = False
.ScreenUpdating = True
End With
MsgBox "The report has successfully been " & vbNewLine & _
"transferred to " & stWordReport, vbInformation
End Sub

VBA Type mismatch error when setting Excel Range in Word

I have the following code as part of my sub trying to assign a range:
'Set xlApp = CreateObject("Excel.Application")
Dim xlApp As Object
Set xlApp = GetObject(, "Excel.Application")
xlApp.Visible = False
xlApp.ScreenUpdating = False
Dim CRsFile As String
Dim CRsMaxRow As Integer
' get the CR list
CRsFile = "CRs.xls"
Set CRsWB = xlApp.Workbooks.Open("C:\Docs\" + CRsFile)
With CRsWB.Worksheets("Sheet1")
.Activate
CRsMaxRow = .Range("A1").CurrentRegion.Rows.Count
Set CRs = .Range("A2:M" & CRsMaxRow)
End With
Dim interestingFiles As Range
' get the files names that we consider interesting to track
Set FilesWB = xlApp.Workbooks.Open("files.xlsx")
With FilesWB.Worksheets("files")
.Activate
Set interestingFiles = .Range("A2:E5")
End With
Do you have any idea why am I getting a run time type mismatch error?
If you run the code from Word then the problem is in the declaration of 'interestingFiles' variable. Range exist in Word as well so use either Variant or add reference to Excel and then use Excel.Range.
Without Excel reference:
Dim interestingFiles As Variant
And with Excel reference:
Dim interestingFiles As Excel.Range
Kindly set xlApp object as in below code.
Also you provide complete path for your workbook when opening it.
Sub test()
Dim interestingFiles As Range
Dim xlApp As Object
Set xlApp = GetObject(, "Excel.Application")
' get the files names
Dim path As String
path = "C:\Users\Santosh\Desktop\file1.xlsx"
Set FilesWB = xlApp.Workbooks.Open(path)
With FilesWB.Worksheets(1)
.Activate
Set interestingFiles = .Range("A2:E5")
End With
End Sub