I have 2 workbooks: "reportPageImpression.xlsx" and "testCloseWorkbook.xslx". Currently I am able to get data from reportPageImpression to testCloseWorkbook when clicking the "Update" button.
What I try to do is when clicking again the "Update" button, the value will go to "Jan-16" (new column) and so on. Here's my code:
Option Explicit
Private Function GetValueFromClosedWorkbook(path, file, sheet, ref)
Dim arg As String
'Let’s check whether the file exists
If Right(path, 1) <> "\" Then path = path & "\"
If Dir(path & file) = "" Then
GetValueFromClosedWorkbook = "File Not Found"
Exit Function
End If
'We create the argument
arg = "'" & path & "[" & file & "]" & sheet & "'!" & _
Range(ref).Range("A1").Address(, , xlR1C1)
'MsgBox arg
'Now we execute an XLM macro
'All references must be given as R1C1 strings.
GetValueFromClosedWorkbook = ExecuteExcel4Macro(arg)
End Function
Sub TestGetValueFromClosedWorkbook()
Dim p As String, f As String
Dim s As String, a As String
p = ThisWorkbook.path
f = "reportPageImpression.xlsx"
s = "report_page_impression"
a = "D39"
ActiveSheet.Range("C8") = GetValueFromClosedWorkbook(p, f, s, a)
End Sub
to check for a cell to be empty you must use a formula like "COUNTA(range)" as the argument of the
ExecuteExcel4Macro(arg)
method and get back the number of non empty cells in the closed workbook specified range.If you specify your cell address as its range and it returns zero then that cell is empty otherwise it has a value and then you can use
ExecuteExcel4Macro(arg)
method again with the cell reference as its argument. In this latter case you may want to use.Offset(rowOffset)
method on your original "Range" to shift to a cellrowOffset
rows apart from it.In order not to get lost in references, I'd suggest you to refactor your code and make extensive use of "wrappers" in order to have clean an maintanable code
Here you may find what I've come up to as per my understanding
the "logic" of shifting to a different cell is all in
var = GetFirstNonEmptyValueFromClosedWorkbook(a, argPart, -1)
where that-1
is the "rowOffsetRate" thatGetFirstNonEmptyValueFromClosedWorkbook(ref As String, argPart As String, Optional rowOffsetRate As Variant) As Variant
function takes into account if the cell in addressa
is empty. if no "rowOffsetRate" is passed then it only checks the cell in addressa