I need to put a link to another Excel files in my current Workbook.
This is the part of my VBA code that does that:
v_fileNameToImport = ThisWorkbook.Path & "\" & v_techs(i) & "\" & v_regions(j) & "\Results\" & v_files(k)
v_sheetName = "RESUMO " & v_regions(j)
'Check if there is already a tab for this region
If (SheetExists(v_sheetName)) Then
Worksheets(v_sheetName).OLEObjects.Add Filename:=v_fileNameToImport, Link:=True, DisplayAsIcon:=True, Top:=40, Left:=160, Width:=100, Height:=100
Else
Set v_sheet = ThisWorkbook.Sheets.Add
v_sheet.Name = v_sheetName
v_sheet.OLEObjects.Add Filename:=v_fileNameToImport, Link:=True, DisplayAsIcon:=True, Top:=40, Left:=40, Width:=100, Height:=100
End If
After running the macro, each file link appears as a blank rectangle instead of an Excel icon. When I click it, it starts to open the other file but crashes right away.
Edit: It seems that when I run the macro for the second time, i.e. after already importing the files, it will crash, despites all tabs are deleted when the macro starts. Maybe the reference to the files remains despites its tabs are deleted, what causes a conflict with a new reference to the same file. When running from a fresh file this problem does not happens.
Related
I am writing a macro in Word, for replacing some text with a mapped definition.
I want to give the user the option to give confirmation for each replace, just like the default Find & Replace.
How can I set focus on the text that is found?
How can the particular section be scrolled into view?
I need to use custom VBA code(rather than default Find & Replace) as I have to process the document after reading in the mappings.
I am already able to replace the text, and also show the alerts to the user.
However, I want to put the focus on the text while showing the alert.
Current code:
Do While myRange.Find.Execute( _
FindText:=dict.Items()(i) & " (" & Word & ")", _
MatchCase:=False, _
MatchWholeWord:=True _
)
myRange.Select
If MsgBox("Replace '" & myRange.Find.Text & "' with '" & Word & "'?", vbYesNo) = vbYes Then
myRange.Text = Word
End If
myRange.Start = myRange.Start + Len(myRange.Find.Text)
myRange.End = cached
Loop
p.s. I have a custom form/dialog open, from which the macro is being run;
so the text is behind the dialog.
EDIT: Based on Jay's response, I again checked the behavior of the Find & Replace dialog. The dialog gets moved based on the location of the text. Can I achieve the same when I have a form and a confirmation dialog over the text?
The statement myRange.Select that's already in your code puts the Selection on the found text, and scrolls it into view if it's offscreen. That won't help, though, if the Selection is hidden behind a custom form (userform?) or the message box. You may be able to move the form out of the way, if you can figure out where the Selection is with respect to the screen coordinates.
I know I've seen references to this issue before, but I have tried several of the suggestions and I am still getting the error. I have a workbook that assembles data from another book and generates a report. I then want to make a new workbook, copy the report information into the new book, save the new book and close it, and then move on to the next report. It should do this around 10 times. In the part of my code where I am copying and pasting the sheets, I am getting an error
Error -2147417848 Automation error The object invoked has
disconnected from its clients
I have checked other postings about this error, and tried the suggested solutions without any results. the interesting thing is that sometimes it will make it through 5 cycles of code before breaking, sometimes only 2. The only consistency is that it always breaks in the same place
fromBook.Sheets("Report").Copy Before:=newBook.Sheets("Sheet1")
I have option Explicit at the top of the module, and I have checked to make sure that there are not any globals inside of the sub it is breaking in. That being said, It's entirely possible I have overlooked something. I also put a "timer" in at one point to make sure that the excel sheets were not walking over each other.
I could really use the help!
Here is my sub's code:
Sub CreateAndSave(ByRef Reg As Integer, ByVal j As Integer)
Dim fromBook As Workbook
Dim fromSheet As Worksheet
Dim newBook As Workbook
Dim fileExists As Boolean
Dim i As Integer
Dim Holder As Integer
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Set fromBook = Application.Workbooks("Region_Audit_Report")
Set newBook = Workbooks.Add
With newBook
.SaveAs Filename:="G:\DataTeam\ExcelDev\Audit Report\Region Workbooks\Region" & Reg & " " & Month(Date) & "-" & Day(Date) & "-" & Year(Date) & ".xlsx" _
, FileFormat:=xlOpenXMLWorkbook
End With
Set newBook = Application.Workbooks("Region" & Reg & " " & Month(Date) & "-" & Day(Date) & "-" & Year(Date) & ".xlsx")
fromBook.Sheets("Report").Copy Before:=newBook.Sheets("Sheet1")
fromBook.Sheets("MonthData").Copy After:=newBook.Sheets("Report")
newBook.Sheets("MonthData").Range("A1") = "Month"
newBook.Sheets("MonthData").Range("B1") = "Store#"
newBook.Sheets("MonthData").Range("C1") = "District"
newBook.Sheets("MonthData").Range("D1") = "Region"
newBook.Sheets("MonthData").Range("E1") = "Due Date"
newBook.Sheets("MonthData").Range("F1") = "Comp Date"
newBook.Sheets("MonthData").Range("G1") = "# of Errors"
newBook.Sheets("MonthData").Range("H1") = "Late?"
newBook.Sheets("MonthData").Range("I1") = "Complete?"
newBook.Sheets("MonthData").Range("A1:I1").Interior.ColorIndex = 43
newBook.Save
newBook.Close
Application.DisplayAlerts = True
End Sub
I have had this problem on multiple projects converting Excel 2000 to 2010. Here is what I found which seems to be working. I made two changes, but not sure which caused the success:
1) I changed how I closed and saved the file (from close & save = true to save as the same file name and close the file:
...
Dim oFile As Object ' File being processed
...
[Where the error happens - where aArray(i) is just the name of an Excel.xlsb file]
Set oFile = GetObject(aArray(i))
...
'oFile.Close SaveChanges:=True - OLD CODE WHICH ERROR'D
'New Code
oFile.SaveAs Filename:=oFile.Name
oFile.Close SaveChanges:=False
2) I went back and looked for all of the .range in the code and made sure it was the full construct..
Application.Workbooks("workbook name").Worksheets("worksheet name").Range("G19").Value
or (not 100% sure if this is correct syntax, but this is the 'effort' i made)
ActiveSheet.Range("A1").Select
I have just met this problem today: I migrated my Excel project from Office 2007 to 2010. At a certain point, when my macro tried to Insert a new line (e.g. Range("5:5").Insert ), the same error message came. It happens only when previously another sheet has been edited (my macro switches to another sheet).
Thanks to Google, and your discussion, I found the following solution (based on the answer given by "red" at answered Jul 30 '13 at 0:27): after switching to the sheet a Cell has to be edited before inserting a new row. I have added the following code:
'=== Excel bugfix workaround - 2014.08.17
Range("B1").Activate
vCellValue = Range("B1").Value
Range("B1").ClearContents
Range("B1").Value = vCellValue
"B1" can be replaced by any cell on the sheet.
You must have used the object, released it ("disconnect"), and used it again. Release object only after you're finished with it, or when calling Form_Closing.
I had this same problem in a large Excel 2000 spreadsheet with hundreds of lines of code. My solution was to make the Worksheet active at the beginning of the Class. I.E. ThisWorkbook.Worksheets("WorkSheetName").Activate
This was finally discovered when I noticed that if "WorkSheetName" was active when starting the operation (the code) the error didn't occur. Drove me crazy for quite awhile.
Couple of things to try...
Comment out the second "Set NewBook" line of code...
You already have an object reference to the workbook.
Do your SaveAs after copying the sheets.
The error in the below line of code (as mentioned by the requestor-William) is due to the following reason:
fromBook.Sheets("Report").Copy Before:=newBook.Sheets("Sheet1")
The destination sheet you are trying to copy to is closed. (Here newbook.Sheets("Sheet1")).
Add the below statement just before copying to destination.
Application.Workbooks.Open ("YOUR SHEET NAME")
This will solve the problem!!
I'd like to be able to add code to a newly created worksheet. The following block of code does that, but will give me an error (pointing to the first line of the code below) if the Visual Basic editor is not open. And, if it is open in the background, it will activate the VB editor window after the macro finishes running.
With wb.VBProject.VBComponents(wb.Worksheets(newSheetName).CodeName).CodeModule
.InsertLines Line:=.CreateEventProc("FollowHyperlink", "Worksheet") + 1, _
String:=vbCrLf & _
"Call FindAllInSheet(Target.Range.Text, Range(Cells(2, 2),Cells(" & num_triple_combos + 1 & ", " & start_triples_col + 1 & ")))"
End With
Is there a way to avoid this behavior?
For now, what I've done that works is by surrounding my code with
Application.VBE.MainWindow.Visible = True
...
Application.VBE.MainWindow.Visible = False
The only issue now is that the macro will cycle through every single existing sheet before adding the code to the designated sheet. I'm not sure why.
Source for my lead: http://www.mrexcel.com/forum/excel-questions/31259-macro-call-visual-basic-editor.html
I'm attempting to use VBA to take in some coordinates from a SQL table, create some code that sits in an excel tab that is then saved as a .kml file and open the file in Google Earth.
When the code creates the kml file it then opens GE but nothing happens (as in, it doesn't show the coordinates in the sidebar and doesn't point to anything).
Similarly, when I navigate to the kml file manually and open it in GE, nothing happens.
However, if I go back to the excel tab that is being saved as .kml, copy/paste the code into notepad and manually save as .kml, the file opens in GE and displays the coordinates from the code.
I have stripped the code back to the minimum required to highlight my problem (see below).
From what I've observed it would seem I'm not saving the file properly.
Sub Mapping()
Range("A1").Value = "<?xml version=""1.0"" encoding=""UTF-8""?>"
Range("A2").Value = "<kml xmlns=""http://www.opengis.net/kml/2.2"""
Range("A3").Value = "xmlns:gx=""http://www.google.com/kml/ext/2.2"" "
Range("A4").Value = "xmlns:kml=""http://www.opengis.net/kml/2.2"" "
Range("A5").Value = "xmlns:atom=""http://www.w3.org/2005/Atom"">"
Range("A6").Value = "<Document>"
Range("A7").Value = " <Placemark> <name>" & "Name here..." & "</name> <description>" & "Testing" & "</description>"
Range("A8").Value = "<Style> <IconStyle> <scale>1.2</scale> <Icon> <href>http://maps.google.com/mapfiles/kml/pal4/icon16.png</href> </Icon> </IconStyle> </Style> "
Range("A9").Value = "<Point> <coordinates>" & " -114.232195463845,53.0160219116952,0" & "</coordinates> </Point> </Placemark>"
Range("A10").Value = "</Document> </kml> "
ActiveSheet.SaveAs "C:\Users\user\Desktop\KMLTESTING4.kml"
Dim KMLLoc As String
KMLLoc = "C:\Users\user\Desktop\KMLTESTING4.kml"
Call Shell("explorer.exe " & KMLLoc, vbNormalFocus)
End Sub
Added FileFormat:=xlTextPrinter to the end of my save and now working fine.
I have a simple VB application which allows the user to select via a tick box a number of interfaces to generate.
I am looping through the ticked entries and for each, I am creating an instance of Excel and executing the appropriate Macro in the workbook.
I am looking to generate the Excel instance in the background for each ticked entry. Currently I have to wait for each Excel instance to run, before I can process the next.
Your help would be greatly appreciated.
Here's the Code Extract:
MsgBox("Starting")
parmExcelAppName = "..{Pathname}\Data Extract v1.4.xlsm"
xlapp = CreateObject("Excel.Application")
xlbook = xlapp.Workbooks.Open(parmExcelAppName)
xlapp.Application.Visible = True
xlapp.Visible = False
parmWorksheetName = "CURRENCY_RATE"
parmWorksheetOutputSaveName = "C:\Users\pete05\Downloads\Interfaces"
parmApplyFilter = "False"
parmRunMode = "REFRESH"
parmAddColumnHeadings = "True"
parmEmailRecipients = "someone#companyname.com"
xlapp.Application.Run("MOD00_RUNMODE.Run_BatchMode ", _
"" & parmWorksheetName & "", _
"" & parmWorksheetOutputSaveName & "", _
"" & parmApplyJDAFilter & "", _
"" & parmRunMode & "", _
"" & parmAddColumnHeadings & "", _
"" & parmEmailRecipients & "")
xlapp.Quit()
MsgBox("Finished")
Ideally the 'Starting' and 'Finished' messages would be displayed almost immediately and the Excel piece pushed into the background. I would then repeat for the next ticked entry.
I can only suggest at this stage that you try this. I don't know if it'll work. I suspect that even opening multiple files like this will open them in the same instance of Excel.
Create an excel file for each required input parameter
Add a startup macro to the excel file to call the macro above when the file opens
Open the excel file using a command line (i.e. excel.exe "c:\book1.xlsx") using the Shell command.
This is just a stab in the dark really. Everything I've read indicates that this either won't work or won't work very well. To make this reliable you need to get the code from MOD00_RUNMODE.Run_BatchMode. If it's just calling a web service for example or reading from a database then you shoud be able to reproduce it outside of Excel and run it in parallel if the feeding system allows it.