ms-access vba - read from excel and also update that excel - excel

Created a simple access DB with only 1 form and 1 one button to run code that opens an existing empty excel (with 1 worksheet) and writes "X" in its 1st cell. It does the job but the workbook is hidden and I have to manually unhide it. That is, after the VBA code is executed I open the excel file and it is all grayed out. I have to click the "view" tab and then select the "Unhide" option and all is fine and I can see that the cell was updated as needed. If I take out the VBA line that writes "X" in the excel file, it doesn't hide the workbook. How do I solve the problem of the workbook being hidden?
Windows 7 and Office2013.
Thank you!!!
Here is the code:
Private Sub Command0_Click()
Dim my_xl_app As Object
Dim my_xl_worksheet As Object
Dim my_xl_workbook As Object
Set my_xl_app = CreateObject("Excel.Application")
my_xl_app.UserControl = True
my_xl_app.Visible = False ' yes. I know it's the default
Set my_xl_workbook = GetObject("D:\Dropbox\MASAV\HIYUVIM\AAA.xlsx")
Set my_xl_worksheet = my_xl_workbook.Worksheets(1)
my_xl_worksheet.Cells(1, "A") = "V"
my_xl_workbook.Close SaveChanges:=True
Set my_xl_app = Nothing
Set my_xl_workbook = Nothing
Set my_xl_worksheet = Nothing
End Sub

S o l v e d !!!
Here is the code that works without hiding my entire workbook :
Private Sub Command0_Click()
Dim my_xl_app As Object
Dim my_xl_worksheet As Object
Dim my_xl_workbook As Object
Set my_xl_app = CreateObject("Excel.Application")
Set my_xl_workbook = my_xl_app.Workbooks.Open("D:\Dropbox\MASAV\HIYUVIM\AAA.xlsx")
Set my_xl_worksheet = my_xl_workbook.Worksheets(1)
my_xl_workbook.Sheets(1).Range("A1").Value = "V"
my_xl_workbook.Close SaveChanges:=True
Set my_xl_app = Nothing
End Sub
Got the answer right here in this this forum, in another thread which escaped my eyes...
Thanks a lot to all in this wonderful forum!!!!

Use this:
Workbooks(1).Windows(1).Visible = True

Related

How to unlock Excel file after opening it trought VBA Word

I'm working on a VBA Word macro to create a personalized agenda. This is done trought the steps:
From VBA Word, open an Excel Spreadsheet
Copy a pre-defined range from the spreadsheet, into an array in Word
Create new Word document, inserting every row from the array on an individual page.
Thanks to the help I found here and on a few websites, I wrote a piece of code that executes these three steps.
After running the code and even closing Word, I get a message everytime I open the spreadsheet in Excel. The message is:
File.xlsm is blocked for edition by 'User' ; (my user)
I think it might be related to:
Calling Excel from VBA Word: I call Excel by creating an ApplicationObject (app_Excel) and using CreateObject method; to finish the application, I used Set app_Excel = Nothing, and then app_Excel.Quit, as seen in the code; Or
Opening a spreadsheet from VBA Word: In the first attempts I was using Excel.Workbooks.Open(,,,ReadOnly = False), then I changed it to True, with the same result.
Sub main()
'Main procedure
Word.Application.ScreenUpdating = False
Dim app_Excel As Excel.Application
Set app_Excel = CreateObject("Excel.Application")
Dim wbk_srce As Workbook
Set wbk_srce = app_Excel.Workbooks.Open("C:\0_portolon\Dias.xlsm", , True)
Dim wsh_srce As Worksheet
Set wsh_srce = wbk_srce.Worksheets(3)
wsh_srce.Activate
cell_1 = CStr("A1")
cell_2 = CStr("D216")
Dim header_range As Excel.Range
wsh_srce.Range(cell_1, cell_2).Select
Set header_range = Excel.Selection
Dim header_array() As Variant
header_array = header_range.Value
Set header_range = Nothing
Set wsh_srce = Nothing
Set sbk_srce = Nothing
app_Excel.Quit
'Creates Word document
Call create_agenda(header_array)
End Sub
How can I unlock the spreadsheet after copying its data into Word?
Thanks in advance,
Tiago
Following the suggestion given in the comments, I changed Set wbk = Nothing to wbk.Close; the code works correctly now.
Thanks.
Sub main()
'Main procedure
Word.Application.ScreenUpdating = False
Dim app_Excel As Excel.Application
Set app_Excel = CreateObject("Excel.Application")
Dim wbk_srce As Workbook
Set wbk_srce = app_Excel.Workbooks.Open("C:\0_portolon\Dias.xlsm", , True)
Dim wsh_srce As Worksheet
Set wsh_srce = wbk_srce.Worksheets(3)
wsh_srce.Activate
cell_1 = CStr("A1")
cell_2 = CStr("D216")
Dim header_range As Excel.Range
wsh_srce.Range(cell_1, cell_2).Select
Set header_range = Excel.Selection
Dim header_array() As Variant
header_array = header_range.Value
Set header_range = Nothing
Set wsh_srce = Nothing
wbk_srce.Close 'change
app_Excel.Quit
'Creates Word document
Call create_agenda(header_array)
End Sub

Pull particular Excel cell value into Word document using Word VBA

I am new to VBA and macros.
I got the repeated task of copy data from Excel and paste it in a particular location in the word document.
For example, my excel sheet has the data like this:
Col1
Col2
ID_1
I'm_One
ID_2
I'm_Two
ID_3
I'm_Three
Now i'm looking for a Word macro
Get text in Word table with cell position 3
Find the same text in Excel Col1
Get the value of Col2 from Excel
Paste the value of Col2 in word table with cell position 10
Repeat the same process for another table in Word document
[Update]
I have tried with multiple code snippets by google search but unable to construct the working macro.
Sub pull_from_Excel2()
'ref: https://www.macworld.com/article/211753/excelwordvisualbasic.html
Dim Month As String
ID_Range = "A2:A6" 'Select this as range like "A2:A16"
Offset_to_fetch = 1 'Select this to fetch comments etc. value starts with
Set xlSheet = GetObject("D:\Excel.xlsx")
'Snippets:
'Debug.Print VarType(xlSheet.Worksheets("Sheet1").Range("A3:A5").Value)
'8204
Dim Cell As Range, rng As Range
Debug.Print VarType(xlSheet.Worksheets("Sheet1").Range(ID_Range).Value2)
Set rng = xlSheet.Worksheets(1).Range(ID_Range)
For Each Cell In rng
Debug.Print Cell.Text
Next Cell
End Sub
I used this url to construct my skeleton code: https://www.macworld.com/article/211753/excelwordvisualbasic.html
When i try to get the values from the range of cells in excel, i got the following error for the code.
Set rng = xlSheet.Worksheets(1).Range(ID_Range).Value2
The above line gives "Object required" error when running.
Set rng = xlSheet.Worksheets(1).Range(ID_Range)
The above line gives "Type Mismatch" error when running.
Notes: For this error, I tried to use for each loop as this is array but the error is showing before executing the for loop.
Kindly assist.
I recommend to use Option Explicit and declare all your varibales properly. This way it is less likely that you end up with unseen errors.
To activate it for all new codes that you add in the future, you can activate it directly in Excel and Word. This is a good practice and will protect you from doing it wrong by notifying you of not declared variables:
In the VBA editor go to Tools › Options › Require Variable Declaration.
This will add Option Explicit to new modules only. In existing modules Option Explicit needs to be added manually as first line.
Further I highly recommend to name your variables according what they contain because otherwise it gets very confusing. You named your variable xlSheet but you load a workbook into it and not a worksheet.
The next issue is that your code is in Word and if you declare rng As Range then this is of type Word.Range and not Excel.Range and those are diffetent types so that is why you get a "Type Mismatch" error.
To solve this you either go in Word VBA to Extras › Refereces … and set a reference to the Excel library so you can declare your variable Dim xlRng As Excel.Range or if you don't set a reference you declare it as Object or Variant like in below example:
' This code is in Word!
Option Explicit
Public Sub pull_from_Excel2()
'declare constants
Const ID_Range As Sting = "A2:A6" 'Select this as range like "A2:A16"
Const Offset_to_fetch As Long = 1 'Select this to fetch comments etc. value starts with
Dim xlWorkbook As Object
Set xlWorkbook = GetObject("D:\Excel.xlsx") 'This expects the Excel to be already open! If not open you need to use CreateObject("Excel.Application")
Dim xlRng As Object
Set xlRng = xlWorkbook.Worksheets(1).Range(ID_Range)
Dim xlCell As Object
For Each xlCell In xlRng
Debug.Print xlCell.Text
Next xlCell
End Sub
Note if your workbook Set xlWorkbook = GetObject("D:\Excel.xlsx") is not open in Excel you need to use CreateObject("Excel.Application") and open it.
Dim xlApp As Object
Set xlApp = CreateObject("Excel.Application")
Dim xlWorkbook As Object
Set xlWorkbook = xlApp.Workbooks.Open(FileName:="D:\Excel.xlsx") 'will open the workbook
xlApp.Visible = True 'make it false to open Excel invisible in the background
'your code here …
'in the end close workbook and Excel (espaciall if you had it invisible!)
xlWorkbook.Close SaveChanges:=False
xlApp.Quit 'close Excel
Option Explicit
Sub UpdateTables()
Const XLSX = "D:\Excel.xlsx"
Dim xlApp, wb, ws
Dim rngSearch, rngFound
Dim iLastRow As Long, n As Integer
' open spreadsheet
'Set xlApp = New Excel.Application
Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = True
Set wb = xlApp.Workbooks.Open(XLSX, 1, 1)
Set ws = wb.Sheets(1)
iLastRow = ws.Cells(ws.Rows.Count, "A").End(-4162).Row 'xlUp
Set rngSearch = ws.Range("A2:A" & iLastRow)
' update tables
Dim doc As Document, tbl As Table, s As String
Set doc = ThisDocument
For Each tbl In doc.Tables
s = tbl.Cell(1, 1).Range.Text
s = Left(s, Len(s) - 2)
Set rngFound = rngSearch.Find(s, LookIn:=-4163, LookAt:=1) ' xlValues, xlWhole
If rngFound Is Nothing Then
MsgBox "'" & s & "' not found in table " & tbl.Title, vbExclamation
Else
tbl.Range.Cells(3).Range.Text = rngFound.Offset(0, 1)
n = n + 1
End If
Next
wb.Close False
xlApp.Quit
MsgBox n & " tables updated", vbInformation
End Sub

Graph portion of Excel table in Word with a macro

So for background, I get a excel workbook from another department that is full of a information for a specific account that I then take and use certain parts to create graphs in word. Is there a way I could create a macro what would grab the data from Ex. C22:H34, put it into a template word document and possibly auto populate the graphs as well? I want to make it a process that I can hand off to other people to do, so the simpler it is to execute, the better.
Here is what I have
Sub AutoNew()
'
' AutoNew Macro
'
'
Dim xlapp As Object
Dim xlbook As Object
Dim xlsheet As Object
Dim bstartApp As Boolean
Dim i As Long
On Error Resume Next
Set xlapp = GetObject(, "Excel.Application")
If Err Then
bstartApp = True
Set xlapp = CreateObject("Excel.Application")
End If
On Error GoTo 0
Set xlbook = xlapp.Workbooks.Open("C:\Users\MattsonC\Documents\work\Copy of
3202_2018_Renewal Rate Workbook v2 EDIT.xlsx")
Set xlsheet = xlbook.Sheets(1)
With xlsheet.Range("A1")
For i = 1 To .CurrentRegion.Rows.Count - 1
ActiveDocument.Variables(.Offset(i, 0)).Value = .Offset(i, 2)
Next i
End With
xlbook.Close
If bstartApp = True Then
xlapp.Quit
End If
Set xlapp = Nothing
Set xlbook = Nothing
Set xlsheet = Nothing
ActiveDocument.Range.Fields.Update
End Sub
I have variables done like {DOCVARIABLE LLY} in all the places I want data to go in the template, and renamed the cells in excel with the same variable name.
I can't get any output to happen in my Word document, any suggestions?
Thank you!
go back to the beginning
insert a document variable in a new word document using following sequence (word 2016)
insert tab … text … quick parts … field … categories: document automation … field names: docVariable … put in variable name xxxx
then run this code
Sub aaa()
'ActiveWindow.View.ShowFieldCodes = Not ActiveWindow.View.ShowFieldCodes ' toggle field code view
Stop
ActiveWindow.View.ShowFieldCodes = True
Stop
ActiveWindow.View.ShowFieldCodes = False
ActiveDocument.Variables("xxxx").Value = "abc123"
ActiveDocument.Range.Fields.Update
Stop
ActiveDocument.Variables("xxxx") = "xyz987"
ActiveDocument.Fields.Update
End Sub
if that works, then use the code with the document that you are having trouble with and figure out if your field names are what you think they are

MS Access VBA format Excel

Hi I am trying to format an excel spread sheet created by my MS access macro. I wanted to select rows with only values in it. So for example I want to select the first row and text wrap it
I thought this logic would work, but gives me error 1004 (Application-defined or Object defined Error)
Dim my_xl_app As Object
Dim my_xl_workbook As Object
Set my_xl_app = CreateObject("Excel.Application")
Set my_xl_workbook = my_xl_app.Workbooks.Open(C:\PATH)
For x = 1 To 23
my_xl_workbook.sheets(x).Range("A1",my_xl_workbook.sheets(x).Range("A1").End(xlToright)).WrapText = True
Next x
my_xl_workbook.Sheets(x).Range("A1", my_xl_workbook.Sheets(x).Range("A1").End(xlToRight)).WrapTex‌​t = True is what is being highlighted when I press debug
Thanks in advance
You are probably not closing properly the file, thus it stays opened and unvisible. Check in your task manager how many excel files do you have opened. Try to close them all. Furthermore, you refer to xlToRight, which is member of the MS Excel Object Library, which is not present in your application.
Thus, try the following:
Public Sub TestMe()
Dim x As Long
Dim my_xl_app As Object
Dim my_xl_workbook As Object
Set my_xl_app = CreateObject("Excel.Application")
Set my_xl_workbook = my_xl_app.Workbooks.Open("C:\Users\v.doynov\Desktop\file.xlsx")
my_xl_app.Visible = True
For x = 1 To my_xl_workbook.Sheets.Count
With my_xl_workbook.Sheets(x)
.Range("A1", .Range("A1").End(xlToRight)).WrapText = True
Debug.Print "Wrapping " & .Range("A1", .Range("A1").End(-4161)).Address & _
" From " & .Range("A1", .Range("A1").End(-4161)).Parent.Name
End With
Next x
my_xl_workbook.Save
my_xl_workbook.Close (True)
End Sub
This is how I found -4161. Add a reference to MS Excel 14.0 Object Library in the Visual Basic Editor.
Then in the immediate window write ?xlToRight. Thats quite enough.

How to retrieve data from Excel and add to Word

I have a Word template file that retrieves data from an Excel file to populate a form.
The code looks something like this:
Dim myXL As Object
Set myXL = Getobject("myfile.xls")
myXL.Application.Visible = True
myXL.Parent.Windows(1).Visible = True
This code works fine in Office 2010 and 2007, but when I try it in 2013, it gives run time error 9 which is an array subscript error. When I check the Windows array it has zero elements, so error is correct.
How do I achieve the same result in 2013?
The next bit of code attempts to access the Worksheets("mysheet") and if I skip the Visible = True line accessing the worksheet gives runtime error 1004.
Any help with fixing this would be greatly appreciated.
To make the code work on Office 2013 I added the line myXL.Activate before trying to make the Window visible. So the code becomes:
Dim myXL As Object
Set myXL = Getobject("myfile.xls")
myXL.Application.Visible = True
myXL.Activate
myXL.Parent.Windows(1).Visible = True
This fixed the run-time error, and the code went back to working well.
To retrieve data from an Excel
An Example would be...
Option Explicit
Sub ExcelData()
Dim xlApp As Object ' Application
Dim xlBook As Object ' Workbook
Dim xlSht As Object ' Worksheet
Dim FilePath As String
FilePath = "C:\Temp\Book1.xlsx"
Set xlApp = CreateObject("Excel.Application")
Set xlBook = xlApp.Workbooks.Open(FilePath)
Set xlSht = xlBook.Sheets("Sheet1")
With ActiveDocument
.Content = xlSht.Range("A1").Value
End With
xlApp.Visible = True
Set xlApp = Nothing
Set xlBook = Nothing
End Sub

Resources