Get value from closed Excel workbook via HTTP link - excel

I have a bunch of Excel workbooks that are stored on a shared online directory (kind of like Dropbox) in different folders. I am creating a master workbook to pull values from these Excel workbooks into a summary. While testing I've managed to create one that works if the workbooks are stored in my disk drives and I refer to their directories, but not via the HTTP links they are stored on.
I'm currently using the ExecuteExcel4Macro macro to retrieve values from closed workbooks on my computer and passing the directory as the argument. Some code for example which works if it's a directory on the hard drive:
Private Function GetValue(path, file, sheet, ref)
' Retrieves a value from a closed workbook
Dim arg As String
' Make sure the file exists
If Right(path, 1) <> "\" Then path = path & "\"
If Dir(path & file) = "" Then
GetValue = "File Not Found"
Exit Function
End If
' Create the argument
arg = "'" & path & "[" & file & "]" & sheet & "'!" & _
Range(ref).Range("A1").Address(, , xlR1C1)
' Execute an XLM macro
GetValue = ExecuteExcel4Macro(arg)
End Function
Sub TestGetValue()
p = "c:\XLFiles\Budget"
f = "Budget.xls"
s = "Sheet1"
a = "A1"
MsgBox GetValue(p, f, s, a)
End Sub
Is there any way to get this to work with direct HTTP links to Excel workbooks instead of directories? Downloading them all into my computer isn't really an option, unless I could somehow change it to download each workbook automatically, get the value and then delete it, or something like that?

Related

Pulling file names from SharePoint and saving to SharePoint, using VBA

I'm trying to adapt an Excel form I created that uses drive locations to save copies of the form, to work with SharePoint in a similar manner. Currently, the first macro is set up such that it will search the contents of a particular folder to determine the next available number in the queue (i.e. if 1, 2 and 4 already exist, it will assign 3) and save the sheet as that next available number. When the sheet is complete, the second macro will save the file with a specified name based on data within the sheet, in another specified location (again based on data defined within the sheet). The drive is in the process of being retired in our company and everything moved to Cloud-based storage, so I would like a way to complete the same actions but using SharePoint directories.
The code for the first macro is as follows:
Dim strDir As String
Dim file As Variant
Dim savename As Integer
Dim savename_string As String
strDir = "R:\Queue\"
savename = 1
savename_string = CStr(savename)
file = Dir(strDir)
While (CInt(savename_string) = savename)
If file <> (savename & ".xlsm") Then
If file = "" Then
savename = savename + 1
Else
file = Dir
End If
ElseIf file = (savename & ".xlsm") Then
savename = savename + 1
savename_string = CStr(savename)
file = Dir(strDir)
End If
Wend
ActiveWorkbook.SaveAs ("R:\Queue\" & savename_string & ".xlsm")
And then the code for the second macro is as follows:
Dim answer As Integer
Dim error As Integer
Dim delete As String
answer = MsgBox("Are you sure you want to save sheet & close?", vbYesNo + vbQuestion, "WARNING")
If answer = vbYes Then
'Define PWO, assembly, terminal, strand, and gauge As Strings, and define which cells they are on the sheet
delete = ActiveWorkbook.Name
ActiveWorkbook.SaveAs ("R:\" & terminal & assembly & Space(1) & gauge & strand & Space(1) & PWO & Space(1) & Format(Now(), "MM-DD-YYYY") & ".xlsm")
Kill ("R:\Queue\" & delete)
ActiveWorkbook.Close
Else
Exit Sub
End If
Currently the second macro works correctly when replacing the locations with the SharePoint URL locations, but when doing the same with the first macro, it returns an error message "Bad file name or number" at the line file = Dir(strDir). Can I get this code in working order, or is there a better way I should go about this? Thanks!

Excel VBA Dir() Error when file type changes

I'm trying to better understand the Dir function. I have a Dir loop to take action on all .csv files in the directory, but when the loop comes across another file type, like .txt, it will error instead of moving on to the next .csv. item.
This is the relevant portion of my code.
strSourceExcelLocation = "\\rilinfs001\Interdepartmental\Billings & Deductions\Billing Coordinators\MCB Reports\East\Monthly Quality MCBs (CMQ & SECMQ)\2019\Individual_Reports\" & fldr & "\"
strWorkbook = Dir(strSourceExcelLocation & "*.csv*")
Do While Len(strWorkbook) > 0
'Open the workbook
Set wbktoExport = Workbooks.Open(Filename:=strSourceExcelLocation & strWorkbook)
'Export all sheets as single PDF
Call Export_Excel_as_PDF(wbktoExport)
'Get next workbook
strWorkbook = Dir
'Close Excel workbook without making changes
wbktoExport.Close False
Loop
So if there are only .csv files in the directory, then this works fine. When it comes across another file type, an error occurs.
The error is on line
strWorkbook = Dir
Run-time error 5: Invalid procedure call or argument
Am I missing something with the way I use the wildcards in the .csv at the beginning?
Thank you
Solved my issue.
The problem seems to have been because when I called another procedure, I had another Dir in that sub to create a new folder if one didn't already exist. So basically I had a Dir in a Dir, which apparently is bad.
I moved the folder creation part to the very beginning of my procedure, so it is executed before I begin the Dir for looping through all the CSV files.
Option Explicit
Sub Loop_Dir_for_Excel_Workbooks()
Dim strWorkbook As String, wbktoExport As Workbook, strSourceExcelLocation As String, fldr As String, strTargetPDFLocation As String, d As String
strTargetPDFLocation = "\\nhchefs001\Accounting\IMAGING\BILLINGS & DEDUCTIONS\EAST MCB FILES\"
'***** Creating a folder to save the PDFs in. Naming the folder with today's date *****
d = Format(Date, "mm-dd-yyyy")
strTargetPDFLocation = "\\nhchefs001\Accounting\IMAGING\BILLINGS & DEDUCTIONS\EAST MCB FILES\" & d & "\"
If Len(Dir(strTargetPDFLocation, vbDirectory)) = 0 Then MkDir strTargetPDFLocation
fldr = InputBox("Input the EXACT Folder Name that you want to create PDFs for")
strSourceExcelLocation = "\\rilinfs001\Interdepartmental\Billings & Deductions\Billing Coordinators\MCB Reports\East\Monthly Quality MCBs (CMQ & SECMQ)\2019\Individual_Reports\" & fldr & "\"
'Search all Excel files in the directory with .xls, .xlsx, xlsm extensions
strWorkbook = Dir(strSourceExcelLocation & "*.csv")
Do While Len(strWorkbook) > 0
'Open the workbook
Set wbktoExport = Workbooks.Open(Filename:=strSourceExcelLocation & strWorkbook)
'Export all sheets as single PDF
Call Export_Excel_as_PDF(wbktoExport, strTargetPDFLocation)
'Close Excel workbook without making changes
wbktoExport.Close False
'Get next workbook
strWorkbook = Dir
Loop
End Sub
Try to hardcode the path and give it a try again. Probably the error is something really small in the hardcoding. E.g., in the code below, replace C:\Users\username\Desktop\AAA\ with the path of the file. Then run it. Do not forget the last \. It should work:
Sub TestMe()
Dim workbookPath As String
workbookPath = Dir("C:\Users\username\Desktop\AAA\" & "*.csv")
Do While Len(workbookPath) > 0
Debug.Print workbookPath
workbookPath = Dir
Loop
End Sub

Consolidating data from multiple excel workbook into master workbook and eliminate duplicate append

I'm stuck in a problem in VBA while consolidating data from other workbook to master work book and using file name and path name is variable which is changing dynamically in loop i searched but i only find hard coded path so i'm posting here following is my code.
Sub Append()
'Append data from other files
Path = "E:\NPM PahseIII\"
Dim c As Range
'find the first empty cell in ColA
Set c = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Offset(2, 0)
Filename = Dir(Path & "*.xlsx")
Do While Filename <> ""
If InStr(Filename, ".") > 0 Then
Filenamenoext = Left(Filename, InStr(Filename, ".") - 1)
End If
c.Value = Filenamenoext
Set c = c.Offset(1, 0)
Workbooks.Open Filename:=Path & Filename, ReadOnly:=True
Windows("Master sheet").Activate
Selection.Consolidate Sources:=Array("'Path & [Filename]Sheet1'!$B$2:$B$5"),
Function:=xlSummary
Workbooks(Filename).Close
Filename = Dir()
Loop
End Sub
The first problem is that this program gives me the error
Object doesn't support this property or method
at this line
Selection.Consolidate Sources:=Array("'Path & [Filename]Sheet1'!$B$2:$B$5"),
Function:=xlSummary
secondly i want that when first time data is appended by running the code again if there is no change in the other files data then code should not append duplicate again.
Note that in that string "'Path & [Filename]Sheet1'!$B$2:$B$5" the Path and Filename is not considered as a variable but as a hard coded string!
You must use something like
"'" & Path & "[" & Filename & "]Sheet1'!$B$2:$B$5"
if you want to use the variable values.
Also according to the documentation of the Range.Consolidate method the constant of the xlConsolidationFunction is not Function:=xlSummary but Function:=xlSum.
Also note that Selection is very undefined and can be anywhere in that worksheet. I recommend to read How to avoid using Select in Excel VBA and reference your ranges, workbooks etc without using .Activate and .Select or Selection. at all.

Using GetValuePrice and receiving error because ref is empty

I am pulling information from worksheets that are in a folder - all files are using the same template - into another worksheet to create a matrix of the information.
I am only pulling three cells from each template and the first two are pulling correctly, because they are on one sheet of the template model but the third is not populating and I am receiving an error.(Run time error 1004. Method of Range of Object_global failed") I am not sure if that has anything to do with my error or if it's something occurring before then.
I have the following:
Private Function GetValuePrice(path, file, sheet, ref)
Dim arg As String
If Right(path, 1) <> "\" Then path = path & "\"
arg = "'" & path & "[" & file & "]" & sheet & "'!" & _
Range(ref).Range("A1").Address(, , xR1C1)
Debug.Assert Var = 0
GetValuePrice = ExecuteExcel4Macro(arg)
End Function
I am receiving an error and when I hit debug it shows me that ref is empty.
(Run time error 1004. Method of Range of Object_global failed")
This is the code i have in the button to pull from the tabs Workload and Project Info from the templates in the folder.
Private Sub CommandButton21_Click()
ThisWorkbook.Sheets("Sheet1").Range("a166:h500").ClearContents
ThisWorkbook.Sheets("Sheet1").Range("j166:v500").ClearContents
Application.Calculation = xlCalculationManual
ProjectInfo
WorkLoad
Application.Calculation = xlCalculationAutomatic
End Sub
I'm not sure what to fix because I run another matrix with the same code but change the file destination and it works.
In my second sub, i was not pulling the correct variable to display in the matrix. I had declared "CC" but was displaying "AA". Therefore changed the AA to CC and it worked.

How to turn this Macro Based function into a genuine VBA function?

I am trying to write a VBA function so that I can access the cell values of a closed Excel Workbook. I found online that one can write a macro routine like this:
Public Sub TestGetValue()
p = "C:\Users\Jake\Desktop"
f = "TestSample.xlsx"
s = "Sheet1"
a = "B10"
Call GetValue(p, f, s, a)
x = GetValue(p, f, s, a)
MsgBox x
End Sub
Public Function GetValue(path, file, sheet, ref)
' Retrieves a value from a closed workbook
Dim arg As String
' Make sure the file exists
If Right(path, 1) <> "\" Then path = path & "\"
If Dir(path & file) = "" Then
GetValue = "File Not Found"
Exit Function
End If
' Create the argument
arg = "'" & path & "[" & file & "]" & sheet & "'!" & _
range(ref).range("A1").Address(, , xlR1C1)
' Execute an XLM macro
GetValue = ExecuteExcel4Macro(arg)
End Function
I can run the TestGetValue() as a macro, but when I try to use GetValue() as a custom VBA function directly in Excel cells it doesn't work. It seems that the line GetValue = ExecuteExcel4Macro(arg) cannot be executed.
Does anyone know how to get around that? I'm using Excel 2010.
As far as I see, the function ExecuteExcel4Macro isn't defined. But there might be an even easier way.
Try to open the Workbook, which contains the desired values. E.g.
Dim tempWb As Workbook
Dim testValue
Set tempWb = Application.Workbooks.Open(path)
testValue = tempWb.Sheets(1).Cells(1,1)
The path can be passed as in your example.

Resources