Weird VBA (Bug?)- Copy Paste Loop Crashes, unless Messagebox is added - vba

I have got a weird problem with VBA. I have programmed a sub that is supposed to create a Word report. I basically have e.g. 10 variablles, a word template document with template charts, and for each variable three CSV files with data. I loop over all variables, and for each variable I create page, access the chartdata workbook, and copy the external CSV data into the chartdata workbook.
Sub createRep()
'open Word-template
for page=1 to 10
'Open external csv
'Open chartdata workbook
'Copy external data into chartdata workbook
'Close external csv files and chartdata workbook
Next page
End Sub
It will work in the beginning, but at a certain page I will get an error because the pasting does not work. I cannot copy anything into the chartdata workbook manually either, it seems like it crashed and that is why the pasting failed. However, the following code will work:
Sub createRep()
'open Word-template
for page=1 to 10
MsgBox page
'Open external csv
'Open chartdata workbook
'Copy external data into chartdata workbook
'Close external csv files and chartdata workbook
Next page
End Sub
That is the message box fixes it somehow. But why?

This is probably due to your code running ahead of Word opening. While the document tries to load, you are already accessing it before the application is ready.
Do fixes to this you could try are just adding DoEvents or if this is not enough, using your reference to the WordApplication do:
While WordApplication.Busy = True
DoEvents
Wend
Hope this helps
-JDB

Related

Excel VBA - close an active table/document by name only - NOT filepath

i have a workbook where i regularly update stock prices from a yahoo link. it opens up a read only file named 'table'. below is an example link
http://real-chart.finance.yahoo.com/table.csv?s=INTC&a=05&b=9&c=2000&d=06&e=7&f=2016&g=d&ignore=.csv
things get messy when i have multiple 'table' file open that results in several additional clicks to import the data.
is there a way i can have a macro where any csv/xls files open named 'table' can be closed?
the function used to get this data is
=HYPERLINK("http://real-chart.finance.yahoo.com/table.csv?s=INTC&a=05&b=9&c=2000&d=06&e=7&f=2016&g=d&ignore=.csv","link")
and i've used similar close workbook scripts before, but i cannot for the life of me figure out how to reference this open file for it to be closed
This assumes that the files open in the same Excel instance as the one running the code, and also that you don't want to save any changes to the open files.
Sub CloseTableWorkbooks()
Dim wb as Workbook
For each wb in Application.Workbooks
If Instr(1, wb.Name, "table") Then wb.Close False
Next
End Sub
Dim book As Workbook
For Each book In Application.Workbooks
if book.name = "table.xls" or book.name = "table.csv" then
book.close
end if
Next
You'll get some messages like "Do you want to save before you close?" or the like, which Excel normally does. You can prevent them too but I'm not sure if you want that or not.

Calling a function from another Excel workbook

I've got a pile of data in one worksheet that I am trying to save to individual workbooks based on values in several columns. The approach I am taking (for better or worse!) is to copy the relevant worksheet (and macros) to a new workbook, save it with an appropriate name (let's say temp.xlsx), and then to cleanse the data in that new workbook by deleting irrelevant rows (function called deleteInfo). This all has to be done without altering the original workbook, as per company policy.
I can copy the stuff over no problem, but I'm having serious issues calling macros in the new workbook then.
I have tried:
Application.Run "'temp.xlsx'!deleteInfo"
ActiveWorkbook.Application.Run deleteInfo
Application.Run ("'C:\user\.....\temp.xlsx'!deleteInfo")
But none have worked.
For the task like this you should consider creating an Excel add-in (file extension .xla) containing VBA macros while keeping the regular Workbooks with data macro-free (extension .xls or .xlsx). More details in Microsoft online article: https://support.office.com/en-ca/article/Add-or-remove-add-ins-0af570c4-5cf3-4fa9-9b88-403625a0b460
Hope this may help.
Solved this issue by exporting the module in which the macro was saved, copying the original workbook and importing it into the new workbook. pathName was defined in previous module to this as the path to the original file's folder (pathName = ActiveWorkbook.Path)
Sub exportMacro(ByVal pathName As String)
'Export the macro to save as .bas file
On Error Resume Next
Kill pathName & "\Module6.bas" 'Delete previously exported file
On Error GoTo 0
ActiveWorkbook.VBProject.VBComponents("Module6").Export pathName & "\Module6.bas"
End Sub
Sub importMacro(ByVal pathName As String)
'import the macro to a new workbook
ActiveWorkbook.VBProject.VBComponents.Import pathName & "\Module6.bas"
End Sub

Excel VBA - Can I manipulate data on another workbook?

Background:
Every month I need to run a report. However, before I can do this, I must export some data in to excel. Once the data is in excel, I have to alter some columns and get the format correct before it is appended to the end of another document to do some analysis on.
What I would like:
I would like to have the document that I append the data to open. I will then export the data in to excel from my program (excel just opens with the data and it is not saved anywhere) and from my larger document, run a VBA script that will alter the data on the other workbook (Book1) so that it can be copied over to the analysis document when in the correct format.
What I have so far:
I have started basic. So far all I am trying to do is set all the cells to the correct height to make it easier to read. However, when I run this code, I get:
Run-time error '9':
Subscript out of range
The code I have so far is:
Sub Data_Ready_For_Transfer()
' Format all cell heights to 15
With Workbooks("Book1.xlsm").Worksheets("Sheet1")
Cells.RowHeight = 15
End With
End Sub
It appears to be having issues with the With Workbooks("Book1.xlsm").Worksheets("Sheet1") part of the code. I have also tried With Workbooks("Book1").Worksheets("Sheet1") and I have tried this with the open, unsaved document and a saved version of the workbook.
Am I missing something obvious?
As follow up from comments, workbook Book1 was opened in another instance of Application object.
In that case this code should work (for already opened workbook):
Sub Data_Ready_For_Transfer()
Dim wb As Workbook
Set wb = GetObject("Book1")
'if we get workbook instance then
If Not wb Is Nothing Then
With wb.Worksheets("Sheet1")
.Cells.RowHeight = 15
End With
End If
End Sub
One more issue, I've changed Cells.RowHeight = 15 to .Cells.RowHeight = 15 to specify, that Cells belongs to workbook Book1 sheet Sheet1.

Vba closing excel applications/workbooks freezes

I have a problem with the following code:
Dim excelapp as object
set excelapp = CreateObject("excel.application")
dim ws as object
dim wb as Workbook
wb= excelapp.Workbooks.Open(path)
ws= wb.Sheets(1)
'in the code i send the worksheet object around by reference in order to read the
'worksheet and manipulate data, i dont create other instances of excel apps or
'workbooks
then i try :
wb.Close
and i have also tried :
excelapp.Quit
Neither have worked, they both freeze and say they are waiting on OLE actions, and i have multiple excel processes opening if i do not call these, when i try to open the excel files i had opened via code, i can only open them as read-only because theyre checked out to me.
I also tried executing a shell script that closes all applications "Excel.Exe" but it closes...the actual excel file where the vba is being executed, so thats not a good solution.
Thank you in advance.
It might be that the Excel app has detected that the workbook has changed and is putting up a dialog box (which is invisible because the app is not visible). Try:
wb.Close False
Which tells Excel to ignore any changes to the workbook.

How to open a file in an active workbook? VB.NET 2008

I have a program that filters data and then outputs it to a tabg delimited file. I then use Excel Interop to open this file in Excel because directly outputting to a worksheet takes too long. So currently I am using this code:
AD.DF.WriteToFile(vbTab)
Dim WB As Workbook = ExcelApp.Workbooks.Open(AD.DF.DatafileInfo.WriteToFileLocation)
ExcelApp.Visible = True
The first line takes the filtered data and outputs to a tab delimited file. The second opens that same file in a new workbook in Excel. And obviously the third makes Excel visible. Here is my problem though: right now when this code is run there are two open workbooks. I already have an active workbook and I would just like to open this file to that workbook.
If this is possible, how do I do it?
Thank you.
Look at the GetObject function.
Dim MyXL As Object
MyXL = GetObject(, "Excel.Application")
should get you a reference to the currently running instance of Excel.
In the code I created an object that is an Excel Workbook. I then set the created workbook as the ExcelApp.ActiveWorkbook. Then I was able to open the file without another workbook being created.