#REF error only first time when copying from closed workbook. Any suggestions? (VBA) - vba

So I am trying to copy/paste some values to reduce runtime of my macro. It is working great, but every time I open the file I want to import the values to, I get #REF in every Cell for a couple of seconds. If I run my macro again, everything works fine and it copies the values as intended.
With wksN.Range("A5:AF200")
.Formula = "='" & Pfad & "[" & Datei &"]Geschäftsvorfälle'!A5:AF200 & """"" '
.Value = .Value
End With
I tried wait for 10 seconds, doevents or calculate if an error exists in the range, but nothing helped, when I execute the code the first time.

Related

Why will this not Autofill?

I am doing a VLOOKUP from a closed workbook. I am using this With statement for it. The first line after the with works. I get the cell from the closed workbook. and it shows up on my open one. The next line where it needs to autofill all the way down does NOT work. It throws an error
"Run time error '1004'. Autofill method of Range class failed."
But if I hit debug and go to the sheet where this is supposed to get auto filled, then hit F8 to continue on and see if it works again, it then works!
So why will this work when I am on the sheet but won't when I am not on the sheet even though the first line works?
With MainWindow.Sheets(1)
.Range("AE2").Formula = "=VLOOKUP($B2,'" & X & "]" & shtName & "'!$B$2:$K$99999,6,FALSE)"
.Range("AE2").AutoFill Destination:=Range("AE2:AE" & Range("B" & Rows.Count).End(xlUp).Row)
End With

Excel vba running differently on two computers

I am pulling my hair out over this as I cannot see why this isn't working. Any help or guidance would be greatly appreciated.
I have inherited a macro in Excel which runs differently depending on which PC we run it on. Essentially, the macro inserts blank rows into a table of data (which should also have conditional formatting to make it blue to break up the table and make it easier to read). On my PC instead of a blank row being entered, it is a row of #ref errors and loses the formatting.
We have a different macro assigned to a button which runs three macros one after another. The one I have the issue with is the third of these three. When I run the macros as three separate events it works, but together it has the #ref errors.
Sorry for the small snippet of the file, but it is sensitive information.
I have tried adding a pause in between the second and third, but this doesn't help.
Are there some security settings which I should check?
The macro looks at a formula in column A and looks for the number 5 and inserts a row after this line. The code is as follows:-
Sub Main()
Dim r As Range
Dim i As Long
i = 1
Do While Range("A" & i).Value <> ""
If Left(Range("a" & i), 2) = "5" Then
i = i + 1
Rows(i).Insert
Range("A" & i).Value = Range("a" & i - 1).Value
End If
i = i + 1
Loop
End Sub
What I am struggling to get my head around is that it works in isolation, but not when run with other macros. For completeness the macro which runs the three has the following code:-
Sub runall_CVR()
Application.ScreenUpdating = False
Call hiderows_CVR
Call Delete0s_cvr
Call Main
Application.ScreenUpdating = True
End Sub
Many thanks
James

Automatic refreshment of Excel DDE RTD

I'm subscribed to a RTD financial application with the option to export real time data to Excel via DDE. So, using the DDE copy/paste app option, I've created a Excel table with real time DDE financial data. Cells actually contains DDE formulas. Now I open, refresh and save table manually, but what I need is a solution that will open, refresh the data, save and close this excel table automatically.
I didn't now how to attach the file, so here is a screenshot of it.
My Excel DDE file
Since I'm new to vba and vbscript, I was searching internet for a solution but without any success, especially not for automatic update (refreshment) of the DDE data.
What I've been doing for the past few days, was searching, trying and customising different kind of vba macros and vbscripts, and today I'm completely lost and confused.
I have tried bunch of suggested solution, even yours
Refresh data and exit with saving Macro Excel
and On workbook open, Excel Macro to refresh all data connections sheets and pivot tables and then export the pivot to csv but in my case they don't work.
Any solution, reference, code example will be greatly appreciated.
Kindly try the below one and
be careful when using
Application.Calculation = xlCalculationManual
Application.Calculation = xlCalculationAutomatic
this sets the entire excel application to calculate formula's either automatically or manually. If you use
Application.Calculation = xlCalculationManual
you'll notice your automatic formulas no longer work.
Thanks for the reply #mulla, but this doesn't work. In vbscript I get runtime error and in vba nothing happens (does not affect refreshment). The same thing is for the Worksheet.Calculate.
Than I recorded a macro upon manual update of the links (data) in order to inspect how Excel proceed update and this actually works, but not all the time. If I open Workbook manually and I keep it opened than whole export works perfectly since the data is constantly refreshed (not what I need). In case when the Workbook is opened via vbscript only (what I need), as you can see in the output below some of the values are exported successfully (for the faster refreshment I believe) and some are #N/A (for the slower refreshment). All the data is refreshed every second, except upon opening the file where successfully exported values are refreshed instantly and #N/A values need few seconds (2-3s) to be refreshed.
Recorder macro uses ActiveWorkbook.UpdateLink as follows (the code below is for the first row, but the same logic is used and for the rest of the rows):
Sub PriceUpdate()
ActiveWorkbook.UpdateLinks = xlUpdateLinksAlways
ActiveWorkbook.UpdateLink Name:= _
"vegadde|VEGA!897789,148,1#""1,\""12,0,0\"""",1", Type:=xlOLELinks
ActiveWorkbook.UpdateLink Name:= _
"vegadde|VEGA!897789,148,1#""1,\""12,0,0\"""",3", Type:=xlOLELinks
ActiveWorkbook.UpdateLink Name:= _
"vegadde|VEGA!897789,148,1#""1,\""12,0,0\"""",4", Type:=xlOLELinks
...
End Sub
Then I use vbscript to call the macro and export data in CSV comma delimited file with timestamp name:
Option Explicit
Dim objExcel, objBook, objSheet
Set objExcel = CreateObject("Excel.Application")
Set objBook = objExcel.Workbooks.Open ("d:\exptest\exptest.xlsm", 0, False)
'Set objSheet = objBook.Worksheets.Item(1)
objExcel.DisplayAlerts = False
objExcel.Run "PriceUpdate"
WScript.Sleep 5000 ' Delay in order to update links
objBook.SaveAs "d:\exptest\" & Year(Now) & "." & Month(Now) & "." & Day(Now) & "_" & Hour(Now) & "-" & Minute(Now) & ".txt",6
objBook.Close False
objExcel.DisplayAlerts = True
objExcel.Quit
'Set objSheet = Nothing
Set objBook = Nothing
Set objExcel = Nothing
And what I get is the following uotput:
Inst,Price,Datetime
USD,1.1015,7/22/2016 12:48
GBP,#N/A,#N/A
CHF,#N/A,#N/A
SEK,9.4962,7/22/2016 12:48
NOK,#N/A,#N/A
JPY,#N/A,#N/A
DKK,#N/A,#N/A
CAD,#N/A,#N/A
AUD,1.47395,7/22/2016 12:48
RUB,71.0082,7/22/2016 12:48
I'm struggling to learn Excel logic behind different updates in order to solve my problem and to get desired solution, but with no success.
And this is only a test file with 22 links. The real one has 482 links that need to be updated.
Marjan. Not sure if this is still a problem for you, but I ran into a similar problem with refreshing RTD data in a closed Excel workbook and seem to have found a solution. As you mentioned, when you open the workbook, the data refreshes automatically (with some of the more complex data points taking 2-3 sec). The problem is, you don't want to have to constantly manually open a workbook to refresh data. And I've found that the data fails to refresh with methods like RTD.RefreshData called to a closed workbook.
So to fix this, I created a vba module that simply opens the workbook, refreshes it, pauses for a second (you may need 2-3 more seconds for all data to update) and then saves and closes the workbook. This method is called recursively. Essentially this does the work of constantly opening and closing the workbook, while delaying briefly so that the RTD data can refresh. So far, this is able to provide refreshed RTD data successfully (although there is an inherent slight delay of a few seconds). Here's the basis of my code:
Sub refreshXLS()
Path = "workbook.xlsm" 'the workbook path you want to refresh
Workbooks.Open Path
ActiveWorkbook.RefreshAll
Application.OnTime Now() + TimeValue("00:00:01"), "closeActive"
End Sub
Sub closeActive()
ActiveWorkbook.Save
ActiveWorkbook.Close
refreshXLS
End Sub
Hope this helps if you still wish to solve this problem!

Run Time error 1004: Select Method of Worksheet class failed with (varCellContent.Parent.Name)

The code edits, then copies data from a temporary sheet to the current workbook. I am using varCellContent to ask the user to choose the source sheet. I had no trouble when testing the code as I was building it by using F8 to step through (and the code still works perfectly like this).
But when I run the macro normally, I am getting
Run Time error 1004: Select Method of Worksheet class failed
on the following line:
Workbooks(varCellContent.Parent.Name).Worksheets("Sheet1").Select
The following may not be relevant to the cause of the problem but I have read a bit about it while searching for an answer.
It sounds like using .Select is not a good idea, but there are 2 reasons I thought it was useful in this situation.
I don't have to name the sheet for each of the following rows of code that delete and move the columns.
When building and debugging the code I wanted the sheet to be visible so that I could see what was happening as I stepped through each line of code.
So taking those 2 reasons into account is there still a better way to avoid using .Select?
Sub ImportNewData()
'
'
' Import data, save as new workbook
Dim LR As Long
LR = Range("A" & Rows.Count).End(xlUp).Row
' Clear data
Range("A3:I" & LR).ClearContents
' User choose source sheet
Dim varCellContent As Worksheet
Set varCellContent = Application.InputBox _
(prompt:=" " & vbNewLine & "Click any cell in the Aged AP Summary that has been exported from Systematic to Excel, then click OK", Type:=8).Parent
Workbooks(varCellContent.Parent.Name).Worksheets("Sheet1").Select
'Delete unrequired columns
Columns("E:I").Select
Selection.Delete Shift:=xlToLeft
Worksheets("Sheet1").Activate
Columns("E:I").Delete Shift:=xlToLeft

VBA VLOOKUP Convert to Values Gives #N/A

I'm having some trouble with VLOOKUP in my VBA. Here's an example of the code I'm using:
Sub Macro15()
'
' Macro15 Macro
Dim LR As Long
LR = Cells(Rows.Count, "A").End(xlUp).Row
Range("B1:B" & LR).FormulaR1C1 = _
"=VLOOKUP(RC[-1],'https://internal_sharepoint_address
/[Vendor_Information.xlsx]Sheet1'!R3C3:R150C18,4,FALSE)"
Range("C1:C" & LR).FormulaR1C1 = _
"=VLOOKUP(RC[-2],'https://internal_sharepoint_address
/[Vendor_Information.xlsx]Sheet1'!R3C3:R150C18,5,FALSE)"
With Range("B1:C" & LR)
.Value = .Value
End With
End Sub
The problem is that the values in Columns B & C (the VLOOKUP formulas) return a value of #N/A.
However, if I stop the code before converting the formula to values (the "With Range("B1:C" & LR)" line), the VLOOKUP formula returns the correct values.
Also strange - if I clear the contents of Columns B & C and re-run the above code, the values return fine. If I try to add a second cycle to the VBA, however, it does NOT work.
Any wisdom that anyone can provide would be a huge help. I've been stuck on this for a long time, and I'm just at my wit's end.
Thanks all,
David
You'll probably need to add in a step that runs a calculation cycle before you try to replace with the value:
Application.Calculate
Edit from comment: I would imagine that retrieving lookup data from a linked workbook on a Sharepoint site would take awhile. Maybe add some delay loops? Can you make two separate macros (one ending with the formulas, and a second one starting at the Paste Values), and run them separately with a pause in between?