Excel Personal.xlsb saving document Macro - vba

I have a macro to see if a cell contains this string if so executes a "save as" command with this set name standard. When I try to run the macro the if statements seem to not work. When I go through step by step it hits the if statements but saves the personal.xlsb instead of the file I'm working on. Here the code I know I have something wrong with it
Dim FName As String
Dim FPath As String
Dim answer As Integer
If ActiveWorkbook.Sheets("Sheet1").Range("A1") = "String1" Then
FPath = "C:\String1"
FName = Sheets("Sheet1").Range("A1").Text
If Len(FPath & "\" & FName) = 0 Then
answer = MsgBox("Do you want to Save File As: " & FName & "?", vbYesNo + vbQuestion, "Microsoft Excel")
If answer = vbYes Then
ThisWorkbook.SaveAs Filename:=FPath & "\" & FName
End If
Else
ThisWorkbook.Save
End If
End If
I am open to suggestion the most I was is to check if the file contains a string if so verify it does not already exist and if so just save instead of save as.

ThisWorkbook refers to the workbook where the code resides. Presumably, the code being in the Personal.xlsb, that is why it's saving the XLSB file and not the activeworkbook.
Try this instead:
Dim FName As String
Dim FPath As String
Dim fullName As String
Dim rng As Range
Dim s as String
s = "String1"
With ActiveWorkbook
Set rng = .Sheets("Sheet1").Range("A1")
If rng.Value = s Then
FPath = "C:\" & s
FName = rng.Text
fullName = FPath & "\" & FName
If Len(fullName) = 0 Then
If MsgBox("Do you want to Save File As: " & FName & "?", vbYesNo + vbQuestion, "Microsoft Excel") = vbYes Then
.SaveAs Filename:=fullName
End If
Else
.Save
End If
End If
End With

Related

Save as CSV saves file with formulas as #NAME?

I have a module function in this report that concatenates certain cells:
Function AnalysisResults(Specs As Range, Results As Range)
AnalysisResults = Join(Specs) & ";" & Replace(Join(Results), ",", ".")
End Function
Private Function Join(Range As Range, Optional ByRef Delimeter As String = " ")
Dim Str As String
For Each cell In Range
If Str <> "" Then Str = Str & Delimeter
Str = Str & cell.Value
Next
Join = Str
End Function
Then i have a command button that save my file as CSV. It works, but the where the function cells are the value saved is #NAME?.
If I Save As manually as CSV comma delimited, it saves correctly and the formula values appears.
Here is the code of the CommandButton:
Dim myValue As Variant
myValue = InputBox("Specifica numele WBT-ului de descarcare:", "Save WBT with the following name", 1)
Range("L2").Value = myValue
Dim CopyToCSV()
Dim MyPath As String
Dim MyFileName As String
Sheets("Manual Discharge WBT").EnableCalculation = True
MyPath = "\\FILES\Transfer\~~TTS Import (do not delete)~~\Import Files\"
MyFileName = Range("L2") & " Discharge " & Format(CStr(Now), " dd_mm_yyyy_hh_mm")
If Not Right(MyPath, 1) = "\" Then MyPath = MyPath & "\"
If Not Right(MyFileName, 4) = ".csv" Then MyFileName = MyFileName & ".csv"
Sheets("Manual Discharge WBT").Copy
With ActiveWorkbook
.SaveAs Filename:= _
MyPath & MyFileName, _
FileFormat:=xlCSVWindows, _
CreateBackup:=False
.Close False
MsgBox "Fisierul tau s-a salvat ca: " & MyFileName
End With
The solution is, you will have to save your AnalysisResults and Join functions as an add-in file .xlam and add to excel at Developer->Add-ins. Doing it this way the above code worked for me when saving to CSV without #NAME?
What was happening here was that when excel is trying to save the file to CSV, it doesn't know what the AnalysisResults function is.

Automatically create at shortcut to a file

I have a small piece of code under a command button click which saves the workbook file with a new name in a new location, I am wondering if it is possible to also automatically create a shortcut to that newly saved workbook in a different location?
Private Sub CommandButton1_Click()
Dim SelectedFNumber As String
Dim DateStr As String
Dim myFileName As String
Dim StorePath As String
DateStr = Format(Now, "dd.mm.yy HH.mm")
SelectedFNumber = Range("B4").Text
If SelectedFNumber <> "SELECT F NUMBER" And Range("D11") > "0" Then
StorePath = "G:\Targets\" & SelectedFNumber & "\"
myFileName = StorePath & SelectedFNumber & " " & DateStr & ".xlsm
If Len(Dir(StorePath, vbDirectory)) = 0 Then
MkDir StorePath
End If
ActiveWorkbook.SaveAs Filename:=myFileName, FileFormat:=xlOpenXMLWorkbookMacroEnabled
Else
MsgBox "Select an F Number"
End If
End Sub
You basically need to add something like this:
Dim sShortcutLocation As String
sShortcutLocation = "C:\blah\workbook shortcut.lnk"
With CreateObject("WScript.Shell").CreateShortcut(sShortcutLocation)
.TargetPath = myFileName
.Description = "Shortcut to the file"
.Save
End With
changing the location to wherever you want.

VBA Excel execute macro in all subfolders, not only particular folders

I am having problems with my code since it only works in the specific folders but not in all subfolders inside the particular folder.
Could someone please helps to make the code works to all subfolders inside that specific folder? :)
These are my code:
Sub Execute1()
Dim monthstr As String
Dim year As String
Dim monthtext As String
Dim prevmonth As String
Dim prevmonthtext As String
year = Range("D8").Text
monthstr = Trim(Range("D9").Text)
monthtext = Trim(Range("D10").Text)
prevmonth = Trim(Range("D11").Text)
prevmonthtext = Trim(Range("D12").Text)
prevyear = Trim(Range("D13").Text)
'confirmation box before running macro//////////////////////////////////////////////////////////////////////////////////////
response = MsgBox("Are you sure the settings are correct?", vbYesNo, "Confirmation")
If response = vbNo Then
Exit Sub
End If
'optimize macro speed///////////////////////////////////////////////////////////////////////////////////////////////////////////
Call Optimize
'finding the correct path (month)//////////////////////////////////////////////////////////////////////////////////////////
Dim myfile As String
Dim mypath As String
Dim newpath As String
mypath = "C:\Users\praseirw\Desktop\Tes CC\" & prevyear & "\SC\" & prevmonth & " " & prevmonthtext & "\"
myfile = Dir(mypath & "*.xlsx")
newpath = "C:\Users\praseirw\Desktop\Tes CC\" & year & "\SC\" & monthstr & " " & monthtext & "\"
'loop through all files in specified month//////////////////////////////////////////////////////////////////////////////////
Dim root As Workbook
Dim rng As Range
Dim wb As Workbook
Dim ws As Worksheet
Set root = Workbooks("CC Reports Center.xlsm")
Set rng = root.Worksheets("Settings").Range("H7:H14")
Do While myfile <> ""
Set wb = Workbooks.Open(mypath & myfile)
For Each ws In wb.Worksheets
rng.Copy
With ws.Range("D1")
.PasteSpecial xlPasteFormulas
End With
Next ws
Dim oldname As String
Dim newname As String
Dim wbname As String
oldname = wb.Name
wbname = Mid(oldname, 9)
newname = year & "_" & monthstr & "_" & wbname
wb.SaveAs Filename:=newpath & newname
wb.Close
Set wb = Nothing
myfile = Dir
Loop
Application.CutCopyMode = False
MsgBox "Task Complete!"
'reset macro optimization settings//////////////////////////////////////////////////////////////////////////////////////////////
Call ResetOptimize
End Sub
Here's one way to do it with the Dir function. If you want something a little more elegant you may want to consider using a FileSystemObject. (Note that to view Debug.Print output you have to enable the immediate window from under view.)
Sub test()
Dim root As String
root = "C:\"
Dim DC As New Collection
s = Dir(root & "*", vbDirectory)
Do Until s = ""
DC.Add s
s = Dir
Loop
For Each D In DC
Debug.Print D
On Error Resume Next: s = Dir(root & D & "\*.xl*"): On Error GoTo 0
Do Until s = ""
Debug.Print " " & s
s = Dir
Loop
Next
End Sub
Here's an example of how to do this with a FileSystemObject. Note that my code is a little sloppy with "On error resume next" to protect against access denied or other errors. Realistically you may want to consider incorporating better error handling, but that's another topic. Using a FileSystemObject is more powerful than Dir because Dir only returns a string, while FileSystemObject lets you work with files and folders as actual objects, which are much more powerful.
Sub test()
'You can use "CreateObject..." to add a FileSystemObject from the Scipting Library
'Alternatively, you can add a reference to "Microsoft Scripting Runtime"
'allowing you to directly declare a filesystemobject and access related intellisense
Set fso = CreateObject("Scripting.FileSystemObject")
Set Folder = fso.GetFolder("C:\")
For Each SubFolder In Folder.SubFolders
Debug.Print SubFolder.Name
On Error Resume Next
For Each File In SubFolder.Files
Debug.Print " " & File.Name
Next
On Error GoTo 0
Next
End Sub

Save as date and time not working

It is supposed to save as file name: Folder\test location 'what ever is in cell C27' and then data and time. I am getting :'008 11 2015 00 00 00'. How do I clean this up with out using "/" and ":"? Note the first 0 is just the test number I used.
Also this macro is in a template that the Testing software uses that is why it has to use Auto_open but the other problem is that when it saves as a non template file, upon opening it tries to run the macro in the non template file. How can I make it so the macro does not save in or is disabled in the save as files/ non template files?
Sub Auto_Open()
Dim FileName As String
Dim FilePath As String
Dim FileDate As String
MyNote = "Is Cell 'C27' Overview Information" & SavePath & " Location_1,2,3,or 4?"
Answer = MsgBox(MyNote, vbQuestion + vbYesNo)
If Answer = vbYes Then
FilePath = "C:\Users\aholiday\Desktop\FRF_Data_Macro_Insert_Test"
FileName = Sheets("Data").Range("C27").Text
ThisWorkbook.SaveAs FileName:=FilePath & "\" & FileName
Dim FileCopyName As String
Dim FileCopyPath As String
FilePath = "C:\Users\aholiday\Desktop\Backup"
FileName = Sheets("Data").Range("C27").Text
FileDate = Format(Date, "mm dd yyyy hh mm ss")
ThisWorkbook.SaveAs FileName:=FilePath & "\" & FileName & FileDate
MsgBox "File was saved!"
MyNote = "Open FRF Data Sheet?(After Forth Test Only)"
Answer = MsgBox(MyNote, vbQuestion + vbYesNo)
If Answer = vbYes Then
Workbooks.Open ("FRF_Data_Sheet_Template.xlsm")
Else
MsgBox "Ready for Next Test, Please Exit."
End If
Else
MsgBox "File was not saved, Please Use Location_1,2,3or,4 Durring SIG ATM Test"
End If
End Sub
Solved:
Sub Auto_Open()
With Range("A30")
.Value = Time
.NumberFormat = "h-mm-ss AM/PM"
End With
Dim FileName As String
Dim FilePath As String
Dim FileDate As String
MyNote = "Is Cell 'B27' Overview Information" & SavePath & " Location1,2,3,or 4?"
Answer = MsgBox(MyNote, vbQuestion + vbYesNo)
If Answer = vbYes Then
FilePath = "C:\Users\aholiday\Desktop\FRF_Data_Macro_Insert_Test"
FileName = Sheets("Data").Range("C27").Text
ThisWorkbook.SaveAs FileName:=FilePath & "\" & FileName
Dim FileCopyName As String
Dim FileCopyPath As String
Dim FileTime As String
FilePath = "C:\Users\aholiday\Desktop\Backup"
FileName = Sheets("Data").Range("B27").Text
FileTime = Sheets("Data").Range("A30").Text
ThisWorkbook.SaveAs FileName:=FilePath & "\" & FileName & FileTime & ".xlsx", FileFormat:=xlOpenXMLWorkbook
MsgBox "File was saved!"
MsgBox "Ready for Next Test, Please Exit."
Else
MsgBox "File was not saved, Please Use Location_1,2,3or,4 Durring SIG ATM Test"
End If
End Sub
You can't have a \ in a filename.
For the date part, use the format function. You can define the date format if you want by using "MM-dd-yyy"
ThisWorkbook.SaveAs FileName:=FilePath & "\" & FileName & Format(FileDate, "MM-dd-yyyy") & ".xlsx", FileFormat:=xlOpenXMLWorkbook
Use the FileFormat:=xlOpenXMLWorkbook to save it as a workbook without macros.

Checking if Folder exists, create new Folder if not, save File from the active workbook either way

I am working on editing some code that was written by someone else and I have had very little Excel Macro experience. I am attempting to save a file to a network location after the code completes. The person who made this program had it being saved to the wrong location and didn't have it checking if the Folder exists or not.
This is what I currently have for grabbing the file for formatting...
It needs to grab the variable file name &MA&.txt from this location...
C:\Twist Check Vaules\&MS& &MP&\$MA%.txt
For example, if MS = TEST and MP = GO and MA = A then...
C:\Twist Check Vaules\TEST GO\A.txt
[Formats File]
Then at the end it needs to check to see if there is already a folder with the same name as the variables above but in a separate location...
Ex. Check for this folder...
O:\diaph\sdata\Blinglet\&MS& &MP&
For example, if MS = TEST and MP = GO...
O:\diaph\sdata\Blinglet\TEST GO
If this folder exists it needs to keep moving on, if not it needs to create it.
Then finally the file by the name of $MA$.txt or using the example, A.txt needs to be saved in that location...
O:\diaph\sdata\Blinglet\TEST GO
I tried looking this up myself but I have been having a lot of trouble since I am so new to excel macro. Any help would be much appreciated!
Sub Polywork_Formating_Macro()
MsgBox ("Polyworks Data Formatting: Autostart Macro in Excel")
Dim idx As Integer
Dim fpath As String
Dim fname As String
Dim MS As String
Dim FileTitle As String
Dim MP As String
Dim MA As String
Dim question As Variant
MS = InputBox("Enter Shop Order:", "File Name")
MP = InputBox("Enter Job Number:", "File Name")
MA = InputBox("Enter A, B , or 360:", "File Name")
FileTitle = " " & MA & ".xls"
idx = 0
fpath = "C:\Twist Check Values\" & MS & "\" & MP & "\" & MA & "\"
fname = Dir(fpath & "*.txt")
While (Len(fname) > 0)
idx = idx + 1
Sheets.Add.Name = fname`enter code here`
With ActiveSheet.QueryTables.Add(Connection:="TEXT;" _
& fpath & fname, Destination:=Range("A2"))
.Name = "a" & idx
[
FORMATTING CODE IN THE MIDDLE REMOVED
]
ActiveWorkbook.SaveAs Filename:="O:\diaph\sdata\Blinglet\" & MS & "\" & MP & "\" & FileTitle & ""
question = MsgBox("Are There AnyMore Files To Be Formated?", vbYesNo)
If question = vbYes Then
Workbooks.Open "C:\Stage Formatter.xlsm"
End If
End Sub
For you file path and name you need double quotes around the strings.
Dim strFilePath as string
str = "C:\Twist Check Vaules\" & MS & MP & "\" & MA & ".txt
For you filesystem functions you will need to reference the library. In the VBA IDE go to the tools menu and select references. Select "Microsoft scripting runtime".
Then you can declare a filesystemobject. That can be used for you folder and file functions.
Dim fldr As Object
Dim strFolder as string
Dim fs As FileSystemObject
Set fs = New FileSystemObject
strFolder = "C:\Twist Check Vaules\" & MS & MP & "\"
If fs.FolderExists(strFolder) = true Then
'Do nothing
else
msbbox ("Folder is missing")
'or you can create it
Set fldr = fs.CreateFolder(strFolder)
If fldr Is Nothing Then
MsgBox "Could not create the folder"
End If
End if
For your text file:
Dim ts As TextStream
Set fs = New FileSystemObject
Set ts = fs.CreateTextFile("C:\Temp\test.txt", True, False)
ts.WriteLine "Whatever text you are writing to the file."
'Clean up
ts.Close: Set ts = Nothing
Set fs = Nothing