ExecuteExcel4Macro, path containing an apostrophe - excel

This will be my first question on this site, so bear with me.
So, I am trying to utilize the ExecuteExcel4Macro function, to reference a value in a different workbook, without having to open the workbook, as it will have to loop through a lot of workbooks in a directory, and reference the same cell on each workbook.
The problem arisen on this line:
wbRef = "'" & folderName & "[" & myDir & "]" & thatSheet & "'!"
which leads to the run-time error 1004 on this line:
month = CStr(ExecuteExcel4Macro(wbRef & Range("D4").Address(, , xlR1C1)))
If, let's say,
folderName = "C:\test\Accounts\O'Malley\Summary\"
, the error occurs.
Since folderName contains an apostrophe, ExecuteExcel4Macro is not recogninzing wbRef as what it is, a path to a folder, but closing that path too early in the path string, therefore resulting the error.
So my question is:
Is there a way to get around this apostrophe, without having to change the folder names, without having to open each individual workbook in the subfolder?
I've tried with double quotations, but didn't seem to do the trick.
Below is a draft of my code, or at least the context.
Sub refMonth()
Dim thisWb as Workbook, folderName as String, myDir as String, wbRef as String, thatSheet as String, month as String
Set thisWb = ActiveWorkbook
folderName = SelectFolder(thisWb)
If folderName = vbNullString Then GoTo Done
myDir = Dir(folderName & "*.xls")
thatSheet = "Sheet1"
wbRef = "'" & folderName & "[" & myDir & "]" & thatSheet & "'!"
Do Until myDir = vbNullString
month = CStr(ExecuteExcel4Macro(wbRef & Range("D4").Address(, , xlR1C1)))
'Do a lot of stuff, which works when in a folder without an apostrophe
myDir = Dir()
wbRef = "'" & folderName & "[" & myDir & "]" & thatSheet & "'!"
Loop
Done:
End Sub
Function SelectFolder(thisWb As Workbook)
Dim diaFolder As FileDialog, DirName As Variant
' Open the file dialog
Set diaFolder = Application.FileDialog(msoFileDialogFolderPicker)
diaFolder.AllowMultiSelect = False
diaFolder.InitialFileName = strFolder(thisWb.Path)
If diaFolder.Show = True Then
'diaFolder.Show
DirName = diaFolder.SelectedItems(1)
If Right(DirName, 1) <> "\" Then
DirName = DirName & "\"
End If
Else
Set diaFolder = Nothing
Exit Function
End If
Set diaFolder = Nothing
SelectFolder = DirName
End Function
Function strFolder(ByVal strFolder0) As String
strFolder = Left(strFolder0, InStrRev(strFolder0, "\") - 1) & "\"
End Function
Any help is appreciated, even if it's just to tell me it's impossible to get around the apostrophe.
I couldn't find an answer on here, but if there is one, please point me in the right direction.

You need to double the apostrophe to escape it:
wbRef = "'" & Replace$(folderName & "[" & myDir & "]" & thatSheet, "'", "''") & "'!"

Related

Loop to save worksheet in new workbook

I want to run through a specific sheet (from & to) save those ws as a new file in a folder, if the folder doesn't exist then create.
I'm able to do it to one sheet.
ActiveSheet.Next.Select
If Range("F3").Value = "" Then
Windows("Import OT.xlsm").Activate
Sheets("Cash").Select
Dim filename101 As String
Dim path101 As String
Application.DisplayAlerts = False
path101 = Environ("UserProfile") & "\Dropbox\A271\5 Oppgjor\" & 2020 & "\"
filename101 = Range("B1").Value & ".xlsx"
ActiveWorkbook.SaveAs path101 & Range("A2") & "\" & Range("A1") & " " & filename101,xlOpenXMLWorkbook
Application.DisplayAlerts = True
Else
Cells.Select
Range("F3").Activate
Selection.Copy
Workbooks.Add
ActiveSheet.Paste
Dim Path1 As String
Dim fpathname1 As String
Path1 = Environ("UserProfile") & "\Dropbox\A271\4 Lonnslipper\"
fpathname1 = Path1 & Range("F3") & "\" & Range("F2") & " " & Range("B3") & ".xlsx"
path01 = Environ("UserProfile") & "\Dropbox\A271\4 Lonnslipper\" & Range("F3")
Dim path001 As String
Dim Folder As String
Folder = Dir(path01, vbDirectory)
If Folder = vbNullString Then
VBA.FileSystem.MkDir (path01)
ActiveWorkbook.SaveAs filename:=fpathname1, FileFormat:=51
ActiveWorkbook.Close
Sheets("Cash").Select
Else
ActiveWorkbook.SaveAs filename:=fpathname1, FileFormat:=51
ActiveWorkbook.Close
Sheets("Cash").Select
End If
End If
End Sub
I want this as a loop is because I have a few tens of sheets. For it to work I think I need to write it specific time, but with loop I learned I don't need to do that.
Excel file sheet
https://onedrive.live.com/view.aspx?resid=AF6FF2618C09AC74!29027&ithint=file%2cxlsx&authkey=!AHcJjYCu8D0NTNY
According to your comment where you wrote the steps:
Read the comments
Try to run the code using F8 key and see where you need to change it.
As you're learning, please note to first write the steps in plain English Norsk and then develop your code.
See how I just followed your steps with readable code.
Code:
Public Sub GenerateCustomersFiles()
' 1) Active sheet (oppgjør 1-20)
Dim targetSheet As Worksheet
For Each targetSheet In ThisWorkbook.Sheets
' Check only sheets with string in name
If InStr(targetSheet.Name, "Oppgjør") > 0 Then
' 2) look if value in F3 is empty
If targetSheet.Range("F3").Value = vbNullString Then
' 3) if it is, do select "cash" sheet and save this file (its name and path are given above what it should be named)
Dim fileName As String
Dim filePath As String
Dim folderPath As String
folderPath = Environ("UserProfile") & "\Dropbox\A271\5 Oppgjor\" & 2020 & "\"
fileName = targetSheet.Range("B1").Value & ".xlsx"
filePath = folderPath & targetSheet.Range("A2") & "\" & targetSheet.Range("A1") & " " & fileName
ThisWorkbook.Worksheets("Cash").Select
ThisWorkbook.SaveAs filePath, xlOpenXMLWorkbook
Else
' 4) if it doesn't, do open selected sheet to a new workbook and save that in clients name folder (folder and path given above in code section)
folderPath = Environ("UserProfile") & "\Dropbox\A271\4 Lonnslipper\" & targetSheet.Range("F3")
fileName = targetSheet.Range("F2") & " " & targetSheet.Range("B3") & ".xlsx"
filePath = folderPath & "\" & fileName
' 5) check if clients folder exist or not for the file to be saved in.
' if folder doesnt exist,
' create new and save file there.
CreateFoldersInPath folderPath
' if folder exist just save the file there
Dim targetWorkbook As Workbook
Set targetWorkbook = Workbooks.Add
targetSheet.Copy before:=targetWorkbook.Sheets(1)
targetWorkbook.SaveAs filePath, 51
targetWorkbook.Close
End If
End If
Next targetSheet
End Sub
' Credits: https://stackoverflow.com/a/31034201/1521579
Private Sub CreateFoldersInPath(ByVal targetFolderPath As String)
Dim strBuildPath As String
Dim varFolder As Variant
If Right(targetFolderPath, 1) = "\" Then targetFolderPath = Left(targetFolderPath, Len(targetFolderPath) - 1)
For Each varFolder In Split(targetFolderPath, "\")
If Len(strBuildPath) = 0 Then
strBuildPath = varFolder & "\"
Else
strBuildPath = strBuildPath & varFolder & "\"
End If
If Len(Dir(strBuildPath, vbDirectory)) = 0 Then MkDir strBuildPath
Next varFolder
'The full folder path has been created regardless of nested subdirectories
'Continue with your code here
End Sub
Let me know how it goes

How to fix "Bad File Name or Number" error when saving an Excel file via macro?

I need to save my excel file using a macro and I am making use of an old macro I made a while ago - which worked just fine. But now, I am getting an error which I don't seem to understand all to well.
Code:
Option Explicit
Sub SaveFile()
Dim strDir As String, saveDate As String, userMachine As String, Filename As String, yearDate As String, monthDate As String, filePath As String
Dim ws1 As Workbook
Set ws1 = Workbooks("Template.xlsm")
Application.DisplayAlerts = False
saveDate = "01/02/2019"
yearDate = Year(saveDate)
monthDate = Format(saveDate, "MMMM")
saveDate = Format(saveDate, "dd-mm-yyyy")
userMachine = "User - 12345"
strDir = "C:\user12345\desktop\Final Results\" & yearDate & "\" & monthDate & "\" & Format(saveDate, "dd-mm-yyyy") & "\"
filePath = ""
Filename = userMachine & " - " & saveDate & ".xlsx"
filePath = Dir(strDir & Filename)
If Dir(strDir, vbDirectory) = "" Then
MkDir strDir
If filePath = "" Then
ws1.SaveAs Filename:=filePath, FileFormat:=51, CreateBackup:=False
Else
MsgBox filePath & " Execution File Exists"
End If
Else
If filePath = "" Then
ws1.SaveAs Filename:=filePath, FileFormat:=51, CreateBackup:=False
Else
MsgBox filePath & " Execution File Exists"
End If
End If
End Sub
The error is on this line filePath = Dir(strDir & Filename) and the error is:
Bad File Name or Number
As far as I can see, my name for the file meets the requirements to save it so I am at a total loss here.
The original code I had was this:
strDir = "C:\username\desktop\" & Format(DateAdd("d", -1, Date), "dd_mm_YY") & "\"
FilePath = Dir(strDir & "myFile.xlsx")
Bad File Name or Number means that the string you are using to save the file is not valid.
You could replace the hardcoded string to your desktop with a relative reference from a function, such as:
Function getDeskTopPath() As String
'Get Desktop path as string
'Command can be exchanged for other information... see list below
'AllUsersDesktop
'AllUsersStartMenu
'AllUsersPrograms
'AllUsersStartup
'Desktop
'Favorites
'Fonts
'MyDocuments
'NetHood
'PrintHood
'Programs
'Recent
'SendTo
'StartMenu
'Startup
'Templates
Dim oShell As Object
Set oShell = CreateObject("Wscript.Shell")
getDeskTopPath = oShell.SpecialFolders("Desktop")
Set oShell = Nothing
End Function

Attach certain files

I want to build the following:
select sheets for pdf printing - works
create folder and print sheets - works
attach those printed files to an email - doesn't work
the filename depends on cell values + Date (last Range.Value in filename), is there a way to get those pdfs attached?
I tried the following, but that doesn't work
'code ...
Dim myDir as String, mySht as String
myDir = "C:\Users\ihlin\OneDrive\Düngung\" & Worksheets("Drip_Drain_Eingabe").Range("s13").Text
mySht = Worksheets("Druckansicht_mmol").Range("c2").Text & "_" & Worksheets("Druckansicht_mmol").Range("K2").Text & "_" & Worksheets("Druckansicht_mmol").Range("P2").Text & "_" & "mmol_" & Worksheets("Druckansicht_mmol").Range("T1").Text
`code ... ...
If CheckBox1 = True Then
.Attachments.Add myDir & "\" & mySht & ".pdf"
End if
If CheckBox2 = True Then
.Attachments.Add myDir & "\" & mySht2 & ".pdf"
If CheckBox1 = True Then
.Attachments.Add myDir & "\" & mySht3 & ".pdf"
End if
If CheckBox1 = True Then
.Attachments.Add myDir & "\" & mySht4 & ".pdf"
End if
Publishing takes forever and ends with crashing Excel.
Any help would be appreciated.
Here is a simple debugging method. Try the following:
.Attachments.Add "c:\somehardcoded\address\ofthe\worksheet\folder\file.pdf"
If it works, then super, you simply have to find a way to represent the folder.
If it does not work, then forget it and try to attach the file in another way.

Error assigning string to object

I'm trying to search for a file, in d:\ folder with the name Division_Application_Partner.xlsx where Division Application and Partner are variables holding string values.
This is the code I gave:
Set WorkbookPath = Dir(path & Division + "_" + Application + "_" + TradingPartner + ".xlsx")`enter code here`
It throws an error saying " Compile Error: Type Mismtach "
Is the name of the file im giving wrong
Here's the code:
Dim WorkbookPath As WorkBook
Dim path as String
Division = Range("C11").Value
Application = Range("C15").Value
TradingPartner = Range("C19").Value
path = "d:\"
'MsgBox (path)
'MsgBox (Division)
'MsgBox (Application)
MsgBox (TradingPartner)
If Len(Dir(path & Division & "_" & Application & "_" & TradingPartner & ".xlsx")) = 0 Then
Set WorkbookPath = Division & "_" & Application & "_" & TradingPartner & ".xlsx"
End If
I tried concatenating using & like you suggested. Still it shows the same error.
You try assign string to object, this why you getting an error
Dim WorkbookPath As WorkBook
Better try
Dim myWkb as Workbook
Set myWkb = Workbooks.Open(your_concat_string)
and dont use reserved words
Application
Finally
Sub test()
Dim wkbExternWorkbook As Workbook
Dim strPath As String
Dim strDivision As String, strApplication As String, strTradingPartner As String
strDivision = Range("C11").Value
strApplication = Range("C15").Value
strTradingPartner = Range("C19").Value
strPath = "D:\"
If Len(Dir(strPath & strDivision & "_" & strApplication & "_" & strTradingPartner & ".xlsx")) <> 0 Then
Set wkbExternWorkbook = Workbooks.Open(strPath & strDivision & "_" & strApplication & "_" & strTradingPartner & ".xlsx")
End If
End Sub
I would start with using & exclusively for string concatenation. The use of + is primarily for adding numbers though it can concatenate strings. However, there are all sorts of caveats to that when using option strict and so forth, so you're better off using what was intended.
The other thing you should do is actually output all those variables before attempting to concatenate or pass them to Dir. Something like:
MsgBox "[" & path & "]"
repeated for all the others as well. The output of that may well point to the problem.
Try this:
Sub test()
Dim application As Variant
Dim division As Variant
Dim WorkbookPath As String
Dim tradingpartner As Variant
Dim path As String
division = Range("C11").Value
application = Range("C15").Value
tradingpartner = Range("C19").Value
path = "d:\"
'MsgBox (path)
'MsgBox (Division)
'MsgBox (Application)
MsgBox (tradingpartner)
If Len(Dir(path & division & "_" & application & "_" & tradingpartner & ".xlsx")) = 0 Then
Workbooks.Add
ActiveWorkbook.SaveAs division & "_" & application & "_" & tradingpartner & ".xlsx"
End If
End Sub
You would first add the workbook and then save it using the created name.

ExecuteExcel4Macro to get value from closed workbook

I found this bit of code and thought it might be good to use if I just need to pull one value from a closed sheet.
strInfoCell = "'" & strPath & "[" & strFile & "]Sheet1'!R3C3"
myvalue = ExecuteExcel4Macro(strInfoCell)
When I run this code I get a value for strinfocell of
'C:\Users\my.name\Desktop[QOS DGL stuff.xlsx]Sheet1'!R3C3
But when I run the code a dialogue pops up, showing desktop files with "QOS DGL suff" showing.
What's causing this, why is it not just pulling back the data as expected?
I know the path and file name are right, because if I copy them from the debug output and paste them in to start>>run then the correct sheet opens.
I know that Sheet1 (named: ACL), does have a value in cells(3,3)
It depends on how you use it. The open file dialog box is being showed to you because the "strPath" doesn't have a "" in the end ;)
Try this code.
Option Explicit
Sub Sample()
Dim wbPath As String, wbName As String
Dim wsName As String, cellRef As String
Dim Ret As String
'wbPath = "C:\Documents and Settings\Siddharth Rout\Desktop\"
wbPath = "C:\Users\my.name\Desktop\"
wbName = "QOS DGL stuff.xls"
wsName = "ACL"
cellRef = "C3"
Ret = "'" & wbPath & "[" & wbName & "]" & _
wsName & "'!" & Range(cellRef).Address(True, True, -4150)
MsgBox ExecuteExcel4Macro(Ret)
End Sub
Similar application, but no hard coded paths as in the examples above. This function copies the value from another closed workbook, similar to the =INDIRECT() function, but not as sophisticated. This only returns the value...not a reference..so it cannot be used with further functions which require references (i.e.: VLOOKUP()). Paste this code into a new VBA module:
'Requires filename, sheetname as first argument and cell reference as second argument
'Usage: type in an excel cell -> =getvalue(A1,B1)
'Example of A1 -> C:\TEMP\[FILE1.XLS]SHEET1'
'Example of B1 -> B3
'This will fetch contents of cell (B3) located in (sheet1) of (c:\temp\file1.xls)
'Create a module and paste the code into the module (e.g. Module1, Module2)
Public xlapp As Object
Public Function getvalue(ByVal filename As String, ref As String) As Variant
' Retrieves a value from a closed workbook
Dim arg As String
Dim path As String
Dim file As String
filename = Trim(filename)
path = Mid(filename, 1, InStrRev(filename, "\"))
file = Mid(filename, InStr(1, filename, "[") + 1, InStr(1, filename, "]") - InStr(1, filename, "[") - 1)
If Dir(path & file) = "" Then
getvalue = "File Not Found"
Exit Function
End If
If xlapp Is Nothing Then
'Object must be created only once and not at each function call
Set xlapp = CreateObject("Excel.application")
End If
' Create the argument
arg = "'" & filename & "'!" & Range(ref).Range("A1").Address(, , xlR1C1)
'Execute an XLM macro
getvalue = xlapp.ExecuteExcel4Macro(arg)
End Function
Code above
strInfoCell = "'" & strPath & "[" & strFile & "]Sheet1'!R3C3"
myvalue = ExecuteExcel4Macro(strInfoCell)
Should read
strInfoCell = "'" & strPath & "[" & strFile & "]" & "Sheet1'!R3C3"
myvalue = ExecuteExcel4Macro(strInfoCell)
It is missing " & "
No need for a function
Cheers
Neil
Data = "'" & GetDirectory & "[" & GetFileName & "]" & Sheet & "'!" & Range(Address).Range("A1").Address(, , xlR1C1)
Address = "$C$3"
GetDirectory = "C:\Users\my.name\Desktop\"
GetFileName = "QOS DGL stuff.xlsx"
Sheet = "ACL"

Resources