Im running a macro in excel externally (from access) using data from an access query.
The macro copies a table of data and pastes it into word.
When excel opens it will run the code before it has had time to refresh the data. Code shown here:
Code
Sub BetterExcelDataToWord()
Dim objWord As Object, objDoc As Object
Dim strFolder As String, strName As String
Dim ws As Worksheet
Dim lngLastRow As Long
On Error GoTo Errorcatch
'------------browse---------------
'--------------------defaulting folder------------------------
With Application.FileDialog(msoFileDialogFilePicker)
.Title = "Select a Folder"
.AllowMultiSelect = False
.ButtonName = "Select"
.InitialView = msoFileDialogViewList
.InitialFileName = "\\server\general\RAMS\RAM_RAMS"
If Right(strName, 1) <> "\" Then
strFolder = strFolder
End If
If .Show <> -1 Then
Exit Sub
Else
strFolder = .SelectedItems(1)
End If
End With
'--------------------defaulting folder------------------------
'------------browse---------------
Dim Ticker As Range
Sheets("RISKS").Activate
Set Ticker = Range(Cells(4, 1), Cells(65, 8))
Ticker.Copy
Sheets("Paste Special").Select
Cells(4, 1).PasteSpecial xlPasteValues
Set ws = ThisWorkbook.Sheets("Paste Special")
lngLastRow = [LOOKUP(2,1/(A1:A65000<>""),ROW(A1:A65000))]
Set objWord = CreateObject("Word.Application")
ws.Range("A4" & ":H" & lngLastRow).Copy
Debug.Print lngLastRow
'open the word doc
With objWord
.Visible = True
Set objDoc = .Documents.Open(strFolder)
'pastes the value of cell at the bookmark
With objDoc.Bookmarks("RISKS").Range
.Characters.Last.Next.PasteAppendTable
'.Tables(1).Rows(1).HeadingFormat = True
End With
.Activate
End With
Set objWord = Nothing: Set objDoc = Nothing
'Clear The Clipboard
Application.CutCopyMode = False
'Application.DisplayAlerts = False
'ActiveWorkbook.Close
'Application.DisplayAlerts = True
Exit Sub
Errorcatch:
'Debug.Assert False
MsgBox err.Description
' This is temporary, if you leave it in it will go into an endless loop so do not forget to remove
'Resume
End Sub
Display More
Note: in the connection properties I have enabled "refresh data when opening file".