Error when determining whether excel file is already open - excel

I was trying to use the code from the following post to determine whether a different excel file is open:
Detect whether Excel workbook is already open
but my code was errorring out every time. After a bit of testing, I determined it appears to be because I have spaces in the filename/path. Is there a way to allow for the file path to include spaces?

You need to wrap the whole path and filename in double quotes if you have spaces in your file name.
So if you have a vba path & file name of:
WBPath = WB.Path & Application.PathSeparator & WBName
You need to add double quotes to the beginning and end of the string.
WBPath = """" & WB.Path & Application.PathSeparator & WBName & """"
What is """"? (The string starts with a " then the next two " " resolve to be a single double quote of text, then the last " ends the string.)
So you are in essence concatenating a Double Quote to the front of the path\file name and to the end.
Hope that helps. :)

Related

VBA ignore System Separators Setting on opening CSV file

In my Windows OS, I set my "Date, time or number formats" with the following separators:
Decimal: ","
Milesimal: "."
List: ";"
In excel, I set in File > Options > Advanced > Use System Separators (ticked)
And when I open my CSV file manually, it goes according to the System Separators (data hidden due to confidential data). In the picture below, each data is in one Column
PROBLEM 1:
But when I asked my VBA macro to Open this CSV file, it totally ignored the System Separators. In the picture below, all data are in the Column A
The command I used in VBA to open the file was:
Workbooks.Open (MacroFile.Range("B" & i).Value & "\" & MacroFile.Range("C" & i).Value), UpdateLinks:=False
Note: It gets the Path + FileName through Cell Content
SOLUTION FOR PROBLEM 1 (credit to #FoxfireAndBurnsAndBurns):
Added property Local:=True to Workbooks.Open (MacroFile.Range("B" & i).Value & "\" & MacroFile.Range("C" & i).Value), UpdateLinks:=False, Local:=True
PROBLEM 2:
When I asked my VBA macro to Close+Save this CSV file, it totally ignored the System Separators. It replaced all the ";" with "," list delimiters
The command I used in VBA to Close+Save the file was:
Workbooks(MacroFile.Range("C" & i).Value).Close SaveChanges:=True
PROBLEM 3:
I've noticed too that when I tried to use the Formula command below, it didn't work, even having Separator as ";"
File_CSV.Range("Z1").Formula = "=SUMIF(F:F;""C"";G:G)"
I had to replace for:
File_CSV.Range("Z1").Formula = "=SUMIF(F:F,""C"",G:G)"
SOLUTION FOR PROBLEM 3 (Credit for TimWilliams):
Used .FormulaLocal in File_CSV.Range("Z1").FormulaLocal = "=SUMIF(F:F;""C"";G:G)"

Sending a string that contains quotations to a file with VBA

I am trying to use VBA build a .jet file, but when I try to append, two possible problems appear. Either it includes all double quotes including the double double quotes like you would normally do in, say, a msgbox, or the string wont work if i remove the double double quotes because the first instance of quotes terminates the string. An example of my code is below (note, the commented/indented areas in the main sub are various possibilities I have tried but without success:
Sheets("Sheet1").Range("A1").Select
Dim MyStr As String
'MyStr = "{" & Chr(34) & "myid" & Chr(34) & ":345," & Chr(34) & "content" & Chr(34) & ":["
'MyStr = "{""myid"":345,""content"":["
'appendToFile ("{""myid"":345,""content"":[")
'appendToFile (MyStr)
End Sub
Sub appendToFile(MyStr As String)
Dim fileName As String
fileName = "MyFile.jet"
Open Application.ActiveWorkbook.Path & "\" & fileName For Append As #1
Write #1, MyStr
Close #1
End Sub
If you want to avoid the extra quotes appearing in your .jet, you can append using the Print # statement, and not the Write # statement.
Unlike the Print # statement, the Write # statement inserts commas between items and quotation marks around strings as they are written to the file.
For example, this code:
Option Explicit
Sub ject()
Dim MyStr As String
MyStr = "{" & Chr(34) & "myid" & Chr(34) & ":345," & Chr(34) & "content" & Chr(34) & ":["
appendToFile (MyStr)
End Sub
Sub appendToFile(MyStr As String)
Dim fileName As String
fileName = "MyFile.jet"
Open Application.ActiveWorkbook.path & "\" & fileName For Append As #1
Print #1,
Close #1
End Sub
will result in:
{"myid":345,"content":[
when opening the .jet file with a text editor.
Is that what you want?

wrong number of arguments error while trying to save?

I keep getting a wrong number of arguments or invalid property assignment error when trying to tack on a password:="xxxxxx" at the end of this line of code.
Wb.SaveCopyAs ThisWorkbook.Path & Application.PathSeparator & _
ValidFileName(Login & " - " & Last & " - " & "Move to $15" & ".xlsx"), Password:="xxxxxx"
What could be causing this? The files saved fine beforehand, but stopped with that error once I tried including a password.
SaveCopyAs doesn't take a password parameter. Only a filename.
Syntax expression. SaveCopyAs( Filename )
expression A variable that represents a Workbook object.
Parameters Name Required/Optional Data type Description
Filename Required Variant Specifies the file name for the copy.

Excel VBA using DIR function with wildcard and values from cell

I'm somewhat new to Excel VBA and am having trouble reading cell values and using them to find a file path and open the file. Here are some of the relevant facts (hopefully this is adequate specificity but please let me know if I am missing other relevant information).
I have the first name and last name of each person in adjoining cells, e.g. first name in F4 and last name in G4.
The files I am trying to open currently all start with "LastName, FirstName" but have different characters after them that don't follow a pattern. I'm trying to use a wildcard to make up for those unknown characters.
All the files are stored in "Z:\Documents\Warehouse Personnel Updates\" and they are all .xlsx files.
Eventually I'm going to create a loop to open multiple files for each person listed, but currently I am just focusing on getting one open.
Here is the code I currently have:
Sub findFile()
Dim Folder As String
Dim FileName As String
Dim FirstName As String
Dim LastName As String
FirstName = Range("F4").Value
LastName = Range("G4").Value
Folder = "Z:\Documents\Warehouse Personnel Updates\"
FileName = Dir(Folder & LastName & ", " & FirstName & "*.xlsx")
Workbooks.Open FileName
When I run this, I get "Run-time error '1004': Sorry, we couldn't find ." Just a space and then a period to end the sentence. It seems like it isn't reading the filename at all.
If anyone has insight to what I am missing, I would appreciate it! Thanks!
You can open a workbook using a wildcard in the Dir. This is just an example...
Dim sName As String
'Declare the variable for the workbook.
sName = Dir(ThisWorkbook.Path & "\*Smith_John*")
If sName <> "" Then
Workbooks.Open Filename:=ThisWorkbook.Path & "\" & sName
End If

Save copy of worksheet as CSV with date in the save name

I need to save a copy of the worksheet I'm using as a CSV file.
The save name is to be the date and the user's name. I set up variables to get this information.
I get
Run-time error '1004'; Application-defined or object-defined error
on the line
Activeworkbook.saveAs Filename
Code is:
Sub SaveCSV()
rundate = DateTime.Now
runname = Application.UserName
savename = rundate & runname
sfilename = ActiveWorkbook.Path & "\" & savename & ".csv"
ActiveWorkbook.Save
ActiveWorkbook.SaveAs Filename:=sfilename, FileFormat:=xlCSV
Application.DisplayAlerts = True
End Sub
Value of rundate (based on default regional settings) will be something similar to below:
3/12/2019 10:25:11
of which forward slash (/) & colon (:) are illegal characters as per the file name conventions in Windows.
To resolve this specific issue, use the below code to assign current-time to the rundate variable:
rundate = Format(DateTime.Now, "dd-MMM-YYYY_hh-mm-ss_")
Another good way is to use generic function because we don't always know what illegal characters are creating the trouble. Because there could be more illegal characters in the filename. Above approach is correct but it's not comprehensive list of illegal characters to remove or replace from the filename before saving it. For eg. these characters are missing from the array in your code -> : & . However it is advised to keep filename rid of other allowed special characters too.
Below, I am providing the function which returns a safe string that can be used to produce filename before saving.
Function ReplaceIllegalCharacters(strIn As String, strChar As String) As String
Dim strSpecialChars As String
Dim i As Long
strSpecialChars = "~""#%&*:<>?{|}/\[]" & Chr(10) & Chr(13)
For i = 1 To Len(strSpecialChars)
strIn = Replace(strIn , Mid$(strSpecialChars, i, 1), strChar)
Next
ReplaceIllegalCharacters = strIn
End Function
Specifically, in your code, replace the ActiveWorkbook.SaveAs line with this line:
ActiveWorkbook.SaveAs Filename:= ReplaceIllegalCharacters(sfilename, "_") & _
, FileFormat:=xlCSV, CreateBackup:=False

Resources