VBA - Run Macro from Word to paste values into Excel - excel

I am relatively new to VBA, and am at a loss as to why I cannot paste into Excel from Word. The following macro ends up pasting the value into Word, even though I think I'm activating the Excel document.
The macro is meant to be run from Word; values from various FormFields then need to be pasted into cells in an existing Excel file.
I searched for a similar issue, though what was returned seemed to be variations of what I am experiencing, and I could not modify those answers to this.
Any help would be appreciated.
Sub Transfer()
Dim WD As Object
Dim ED As Excel.Application
Dim EDS As Excel.Workbook
Set WD = ActiveDocument
Set ED = CreateObject("excel.application")
ED.Visible = True
Workbooks.Open FileName:= _
"C:\Users\Documents\AppealData.xlsx"
ActiveWorkbook.Activate
Set EDS = ActiveWorkbook
WD.FormFields("AppNum").Copy
EDS.Activate
EDS.Sheets("Sheet1").Range("A1").Select
Selection.Paste
End Sub

Your Selection is referring to the current application. To refer to the Excel application you need to use ED.Selection. But it is a bad idea to rely on Activate and Select anyway.
I suggest you change your code to:
Sub Transfer()
Dim WD As Document
Dim ED As Excel.Application
Dim EDS As Excel.Workbook
Set WD = ActiveDocument
Set ED = CreateObject("excel.application")
ED.Visible = True
'Avoid "Activate"
Set EDS = ED.Workbooks.Open(FileName:= _
"C:\Users\Documents\AppealData.xlsx")
WD.FormFields("AppNum").Copy
'Avoid "Activate" and "Select" and "Selection"
'"Paste" is a worksheet Method, use "PasteSpecial" for a Range
'Use "xlPasteValues" to avoid formatting issues
EDS.Sheets("Sheet1").Range("A1").PasteSpecial Excel.xlPasteValues
End Sub

This here should work for you.
Sub Transfer()
Dim oExcel As Excel.Application
Dim oWB As Workbook
Set oExcel = New Excel.Application
Set oWB = oExcel.Workbooks.Open("C:\Users\Documents\AppealData.xlsx")
oExcel.Visible = True
Workbooks("Book1").Worksheets("Sheet1").Cells(1, 1).Value = _
CStr(Documents("Document1").FormFields("AppNum").Result)
End Sub

Related

Access/Excel VBA Failing

I have an Access database that runs a macro that opens some Excel files and formats the sheets to prepare them for later use. This code has been running fine until my company applied the latest Office Updates, and now I am getting a compile error "Method or data member not found" and its happening on the line...
wDate = Mid(XlSheet.Range("B4").Value, 13, Len(XlSheet.Range("B4").Value))
singling out the "Range". I cannot figure out why this started happening. Thanks for any assistance. Full code below...
Function ExcelProcess()
'Variables to refer to Excel and Objects
Dim MySheetPath As String
Dim Xl As Excel.Application
Dim XlBook As Excel.Workbook
Dim XlSheet As Excel.Worksheet
Dim MyFile As Variant
Dim MySheet As Variant
Dim wBook As Variant
Dim wSheet As Variant
Dim wDate As Variant
Dim rng As Range
Dim cel As Range
MyFile = Array("w1.xlsx", "w2.xlsx", "w3.xlsx")
MySheet = Array("T2_IND", "APPR_IND", "SLG_APPR_IND", "SLG_IND", "C2A_IND", "C3_IND", "C4_IND", "T3_IND", "T4_IND", "C2B_IND")
For Each wBook In MyFile
' Tell it location of actual Excel file
MySheetPath = "\\fs1\Training\CSC_Training_Ops\Training Only\Buzzard\Pulled Data\" & wBook
'Open Excel and the workbook
Set XlBook = GetObject(MySheetPath)
'Make sure excel is visible on the screen
XlBook.Windows(1).Visible = True
For Each wSheet In MySheet
'Define the sheet in the Workbook as XlSheet
Set XlSheet = XlBook.Worksheets(wSheet)
wDate = Mid(XlSheet.Range("B4").Value, 13, Len(XlSheet.Range("B4").Value))
XlSheet.Range("A15").FormulaR1C1 = "WE_Date"
If XlSheet.Range("A16").Value <> "No data found" Then
Set rng = XlSheet.Range(XlSheet.Range("A16"), XlSheet.Range("A16").End(xlDown).Offset(-1))
For Each cel In rng.Cells
With cel
.FormulaR1C1 = wDate
.NumberFormat = "m/d/yyyy"
End With
Next cel
End If
XlSheet.Rows("1:14").Delete Shift:=xlUp
XlSheet.Range("A1").End(xlDown).EntireRow.Delete Shift:=xlUp
Next
XlBook.Close SaveChanges:=True
Next
'Clean up and end with worksheet visible on the screen
Set Xl = Nothing
Set XlBook = Nothing
Set XlSheet = Nothing
End Function
There isn't any apparent problems with the code itself.
Since this broke with when you updated the office, I would venture a guess that it is an issue with the reference.
Go to Tools->References->
Remove all references to Excel Object Library
Save & Close the Macro Worksheet (Shouldn't be necessary, but only takes a sec)
Re-Open
Add in reference to only the latest version of Microsoft Excel 1X.0 Object Library
If this does not solve the issue, you may have to run a repair on office
Control Panel -> Add Remove Programs
Locate Microsoft Excel (Or office suite)
Run Repair
Finally, it was suggested to try late binding. Remove the references to the Microsoft Excel Object Library and update your declarations to:
Dim Xl As Object
Dim XlBook As Object
Dim XlSheet As Object
Set Xl = CreateObject("Excel.Application")
Hope this helps!
Is it possible you got upgraded from Office 14.0 to 15.0 or 16.0? Hit Alt+F11 > Tools References and look for errors in the window that opens. Search for the correct reference and click it. As others have suggested, consider rewriting the code using some late binding methodologies.

Using xlpastevalues in Access VBA

I am working in Access and need to pull data from an Excel file. The file is very large with several sheets that I don't need, so I want to take the values from one sheet and put them in a new workbook in order to simplify/speed up later calculations. Currently, it is including formatting along with the values and some of my later macros are not working even though they worked when I manually pasted the values into the new sheet. I tried running this directly in Excel (removing the references to the Excel.Application variable) and it worked fine. Is there something different I should be doing since this is being run in Access?
Private Sub CopyImportFile()
Dim xl As Excel.Application
Dim SourceBook As Excel.Workbook
Dim SourceSheet As Excel.Worksheet
Dim ImportBook As Excel.Workbook
Dim ImportSheet As Excel.Worksheet
Dim SourceSheetPath As String
SourceSheetPath = "File Path"
Set xl = CreateObject("Excel.Application")
Set SourceBook = GetObject(SourceSheetPath)
Set SourceSheet = SourceBook.Worksheets("Data Tape")
Set ImportBook = xl.Workbooks.Add()
SourceSheet.UsedRange.Copy
ImportBook.Sheets(1).Cells(1,1).PasteSpecial Paste:=xlPasteValues
xl.ActiveWorkbook.SaveAs FileName:="New File Path"
SourceBook.Close False
ImportBook.Close
Set xl = Nothing
Set ImportBook = Nothing
Set SourceBook = Nothing
Set ImportSheet = Nothing

VBA Using Outlook to open excel not opening

Hi Thanks for your help.
I have the follow code in Outlook 2010 & 2007:
Sub Openexcel()
Dim xlApp As Object
Dim sourceWB As Workbook
Dim sourceSH As Worksheet
Dim strFile As String
Set xlApp = CreateObject("Excel.Application")
With xlApp
.Visible = True
.EnableEvents = False
End With
strFile = "E:\All documents\susan\work\Excel projects\saving files to directory Clean.xls"
Set sourceWB = Workbooks.Open(strFile, , False, , , , , , , True)
Set sourceSH = sourceWB.Worksheets("Sheet2")
sourceWB.Activate
End Sub
This code works the first time I use it after opening outlook but if I then close the excel file I can not use it again. I need to reopen this work book about 3 times
The Question at
Outlook VBA open excel
seen to have the same problem but I did not understand the answer.
"I got it figured out. I was opening a different workbook and then closing it before I try to open the second one and that was interfering with it. To fix this I kept the excel app open and reset the workbook object to the new workbook i wanted"
If some someone could help with the additional code that would be great.
Great code found at Excel interactions don't work after Excel file opened.
why I could not find this last week who knows.
Sub Openexcel()
' change
Dim xlApp As Excel.Application
Dim sourceWB As Excel.Workbook
Dim sourceSH As Excel.Worksheet
'change
Set xlApp = New Excel.Application
With xlApp
.Visible = True
.EnableEvents = False
'.UserControl = False
'.DisplayAlerts = False
'.AskToUpdateLinks = False
End With
strFile = "E:\All documents\susan\work\Excel projects\saving files to directory Clean.xls"
'change
Set sourceWB = xlApp.Workbooks.Open(strFile, , False, , , , , , , True)
Set sourceSH = sourceWB.Worksheets("Sheet2")
sourceWB.Activate
End Sub
Thanks guys for all your thoughts.
You need to declare the Excel Applicaton at the global scope and use it to open another workbooks. Not to create a new Excel instance for opening new files. You may find the How to automate Microsoft Excel from Visual Basic article helpful.
For example, declare the Application object outside the event handler:
Dim oXL As Excel.Application
Private Sub Command1_Click()
Dim oWB As Excel.Workbook
Thus, you will be able to re-use it for closing and opening new workbooks.

Word VBA to solve linebreak or paragraph mark issue when copy & Paste into excel

I have managed to copy and paste a table in word using VBA into excel but the end result isn\t quite what I have expected.
There is this problem of a linebreak issue in some of my cells that I would like to solve.
For example,
I have a text in a table in word with certain linebreak like
"This is a sunny day and we have the following options:"
a) Go shopping
b) Stay Indoor
The problem with this is that once it is imported into excel, point a and b is no longer in the same cell in excel. Excel inserted it as a new cell each instead of formatting the points into a single cell.
I have tried to use find and replace to replace the linebreak ^p into blank but the letter a and b would be removed as space. I don't want to replace my a and b as space. I still need them to be inserted into the excel cell.
Sub CreateExcel()
Dim xlApp As Excel.Application
Dim xlWB As Excel.Workbook
Dim tableWord As Word.Table
Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = False
Set xlWB = xlApp.Workbooks.Add ' create a new workbook
'declare the cell to put the text in
With xlWB.Worksheets(1)
Set tableWord = ActiveDocument.Tables(1)
tableWord.Range.Copy
.Paste Destination:=xlWB.Worksheets(1).Range("A1")
xlApp.Dialogs(xlDialogSaveAs).Show
End With
xlWB.Close False ' close the workbook without saving
xlApp.Quit ' close the Excel application
Set xlWB = Nothing
Set xlApp = Nothing
End Sub
You can try to search & replace with the Carriage Return character: Chr(10)
[EDIT]
Well, i can't find a way to deal straight forward with your issue, maybe a better vba expert may find a solution.
The workaround i found is to concatenate the values of the cell after you pasted them because there is no other way to keep formatting either (i adapted my Excel code to make it usable in Word vba):
Option Explicit
Sub CreateExcel()
Dim xlApp As Excel.Application
Dim xlWB As Excel.Workbook
Dim tableWord As Word.Table
Dim cell As Excel.Range, rUsed As Excel.Range, target As Excel.Range
Dim val As String
Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = True
'xlApp.Visible = False
Set xlWB = xlApp.Workbooks.Add ' create a new workbook
'declare the cell to put the text in
With xlWB.Worksheets(1)
Set tableWord = ActiveDocument.Tables(1)
tableWord.Range.Copy
.Paste Destination:=xlWB.Worksheets(1).Range("A1")
'Select used range to get every cell that was pasted and has content
Set rUsed = xlWB.Worksheets(1).UsedRange
Set target = rUsed.Cells(1, 1)
'Get the value of each cell and concatenate its value
For Each cell In rUsed
If cell.Value <> "" Then
val = val + cell.Value + Chr(10)
cell.ClearContents
End If
Next cell
'Remove last carriage return
target.Value = Left(val, Len(val) - 1)
xlApp.Dialogs(xlDialogSaveAs).Show
End With
xlWB.Close False ' close the workbook without saving
xlApp.Quit ' close the Excel application
Set xlWB = Nothing
Set xlApp = Nothing
End Sub
Regards,
Max

how to print excel file via vb6?

I have an excel file that was created by vb6 application and after I save it, I want it to be printed into the default printer..,
Tnx, any help would be appreciated.
Private Sub Command1_Click()
Dim xlApp As Excel.Application
Dim xlWB As Excel.Workbook
Dim xlSH As Excel.Worksheet
'open excel application
Set xlApp = New Excel.Application
'Open excel workbook
Set xlWB = xlApp.Workbooks.Open(FileName:="C:\YourFile.xls")
'There are two ways to access specific worksheets
'By index number (the first worksheet in this case)
Set xlSH = xlWB.Worksheets(1)
'or by the Sheet's Name
Set xlSH = xlWB.Worksheets("TestSheet")
PrintSheet xlSH, "MyFoot", "MyHead"
'Close workbook (optional)
xlWB.Close
'Quit excel (automatically closes all workbooks)
xlApp.Quit
'Clean up memory (you must do this)
Set xlWB = Nothing
Set xlApp = Nothing
End Sub
Sub PrintSheet(sh As Worksheet, strFooter As String, strHeader As String)
sh.PageSetup.CenterFooter = strFooter
sh.PageSetup.CenterHeader = strHeader
sh.PrintOut
End Sub
Yet, to answer your question, you can use :
ActiveWorkbook.PrintOut Copies:=1, Collate:=True
and you can find much information here : http://www.exceltip.com/excel_tips/Printing_in_VBA/210.html
Anyway, i insist, you should accept answers from your previous questions or people won't care answering your new ones.
Max

Resources