I want to have a shared excel document, I want to know how many users have viewed it, basically its viewing history. I have checked for google sheets but that feature is only available for people with company domains not for individual. If anything apart from google sheet that can track the viewing history will also do. Please suggest
In the Workbook.Open event, make a call to this Sub. The user name, machine name and what time the user opened the file will be part of the filename. You can save more information when the code opens the file (see the code comment when printing to file):
Sub fnSaveAccessLog()
Dim strLogFile As String
Dim lngFF As Long
Dim strMachine As String
Dim strUser As String
Dim strDate As String
Dim strFileName As String
On Error Resume Next
MkDir ThisWorkbook.Path & "\Logs"
On Error GoTo 0
strLogFile = "UserAccess"
strMachine = Environ("computername")
strUser = Environ("username")
strDate = Year(Now) & Format(Month(Now), "00") & Format(Day(Now()), "00") & "_" & _
Format(Hour(Now()), "00") & Format(Minute(Now()), "00") & Format(Second(Now()), "00")
strFileName = ThisWorkbook.Path & "\Logs\" & strLogFile & "_" _
& strDate & "_" & strUser & "_" & strMachine & ".txt"
lngFF = VBA.FreeFile
Open strFileName For Output As #lngFF
Print #lngFF, "put more info here if desired"
Close #lngFF
End Sub
After reading #indnwkybrd's comments I modified the code, to implement the two commented suggestions (thanks!) and simplified the construction of the filename variable.
Option Explicit
Sub fnAppendAccessLog()
Dim lngFF As Long
Dim strMachine As String
Dim strUser As String
Dim strDate As String
Dim strFileName As String
On Error Resume Next
MkDir ThisWorkbook.Path & "\Logs"
On Error GoTo 0
strMachine = Environ("computername")
strUser = Environ("username")
strDate = Format$(Now, "yyyyMMDD_hhmmss")
strFileName = ThisWorkbook.Path & "\Logs\" & "UsersAccessLog - " & Split(ThisWorkbook.Name, ".")(0) & ".txt"
lngFF = VBA.FreeFile
Open strFileName For Append As #lngFF
Print #lngFF, Join$(Array(strUser, strMachine, strDate), vbTab)
Close #lngFF
End Sub
Related
So i have found 2 macros which i want to use to save and create a back up files for the said file.
The Macro which i want to primarily use is this one:
Sub DateFolderSave()
Dim strGenericFilePath As String: strGenericFilePath = "D:\"
Dim strYear As String: strYear = Year(Date) & "\"
Dim strMonth As String: strMonth = MonthName(Month(Date)) & "\"
Dim strDay As String: strDay = Day(Date) & "\"
Dim strFileName As String: strFileName = "_Dispatch Process_"
Application.DisplayAlerts = False
' Check for year folder and create if needed
If Len(Dir(strGenericFilePath & strYear, vbDirectory)) = 0 Then
MkDir strGenericFilePath & strYear
End If
' Check for month folder and create if needed
If Len(Dir(strGenericFilePath & strYear & strMonth, vbDirectory)) = 0 Then
MkDir strGenericFilePath & strYear & strMonth
End If
' Check for date folder and create if needed
If Len(Dir(strGenericFilePath & strYear & strMonth & strDay, vbDirectory)) = 0 Then
MkDir strGenericFilePath & strYear & strMonth & strDay
End If
' Save File
ActiveWorkbook.SaveAs FileName:= _
strGenericFilePath & strYear & strMonth & strDay & strFileName, _
FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
Application.DisplayAlerts = True
' Popup Message
MsgBox "File Saved As: " & vbNewLine & strGenericFilePath & strYear & strMonth & strDay & strFileName
End Sub
So i found this another Macro which make continuous back up of the files and has a custom format to a file name
Sub Save_Backup(ByVal Backup_Folder_Path As String)
Dim fso As Object
Dim ExtensionName As String, FileName As String
Dim wbSource As Workbook
Set fso = CreateObject("Scripting.FileSystemObject")
Set wbSource = ThisWorkbook
ExtensionName = fso.GetExtensionName(wbSource.Name)
FileName = Replace(wbSource.Name, "." & ExtensionName, "")
fso.CopyFile ThisWorkbook.FullName, _
fso.BuildPath(Backup_Folder_Path, FileName & " (" & Format(Now(), "dd-mmm-yy hh.mm AM/PM") & ")." & ExtensionName)
Set fso = Nothing
Set wbSource = Nothing
End Sub
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
Call Save_Backup("C:\Users\admin\Downloads\Back Up\New Backup")
End Sub
So i want to create back up like the first macro(i.e. Folder inside a folders for the specific date) but want to have a continuous stream of files for back up(i.e. Want the date folder to create new save file each time i save the Document)
Is there a way to combine both these macros?
I would like to:
open all .csv files in the same folder.
save a copy each in .xlsx format.
with the .xlsx format file name as the Range(“B1”).Value from the corresponding .csv file.
Here is my code so far (not working):
Dim MyFolderPath As String
MyFolderPath = Application.DefaultFilePath
myFolderPath = Application.DefaultFilePath
MyFileName = Dir(myFolderPath & "\" & "*.csv")
While MyFileName <> ""
Set CSVWorkbook = Workbooks.Open(myFolderPath & "\" & MyFileName)
CSVWorkbook.SaveCopyAs Filename:=myFolderPath & "\" & CSVWorkbook.Sheets(1).Range("B1").Value & ".xlsx"
CSVWorkbook.Close SaveChanges:=False
Wend
Could anyone help me to identify the issue?
Many thanks!
Hello TropicalMagic...
try this
`Sub test()
Dim MyFolderPath As String
Dim CSVworkbook As Workbook
Dim MyfileName As Variant
Dim NewFilename As String
MyFolderPath = Application.DefaultFilePath
MyfileName = Dir(MyFolderPath & "\" & "*.csv")
While MyfileName <> ""
Set CSVworkbook = Workbooks.Open(MyFolderPath & "\" & MyfileName)
NewFilename = CSVworkbook.Sheets(1).Range("B1").Text
CSVworkbook.SaveCopyAs fileName:=MyFolderPath & "\" & NewFilename & ".xlsx"
CSVworkbook.Close SaveChanges:=False
MyfileName = Dir
Wend
End Sub`
Another point to mention. Ensure you have data in the Sheets(1) "b1" range.
If you open an empty CSV in excel and put something in B1, Save it and reopen and you will see the text in B1 will have moved to A1 due to the way excel interprets CSV's and there being no control or delimiters in an empty CSV Spread sheet. To get around this put something in A1.
Thanks for responding! I have found a solution as well:
Dim MyFolderPath As String
Dim CSVworkbook As Workbook
Dim MyFileName As Variant
Dim NewFileName As String
MyFolderPath = Application.DefaultFilePath
MyFileName = Dir(MyFolderPath & "\" & "*.csv")
While MyFileName <> ""
Set CSVworkbook = Workbooks.Open(MyFolderPath & "\" & MyFileName)
NewFileName = CSVworkbook.Sheets(1).Range("B1").Text
CSVworkbook.SaveAs MyFolderPath & "\" & NewFileName & ".xlsx", xlOpenXMLWorkbook
CSVworkbook.Close SaveChanges:=False
MyFileName = Dir
Wend
Cheers
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
I am writing a code but dont know what the syntax is. I just want my code to search and find a pdf
Sub open1()
Dim pdfname As String
Const sPath = "S:\PROFILE ORDERS\"
Dim path1
pdfname = Application.InputBox("Enter the pdf you are looking for")
pdfname = pdfname & ".pdf"
path1 = Dir(sPath & pdfname)
path1.Open
End Sub
Sub OpenPdf()
On Error GoTo OpenPdf_Error
Dim pdfname As String
Dim pdf
Const sPath = "S:\RA QUOTES 2019"
Dim FName As String
Dim arNames() As String
Dim myCount As Integer
Dim i As Integer
FName = Dir("S:\RA QUOTES 2019\*.pdf*")
Do Until FName = ""
myCount = myCount + 1
ReDim Preserve arNames(1 To myCount)
arNames(myCount) = FName
FName = Dir
Loop
pdfname = Application.InputBox("Enter the pdf you are looking for")
pdfname = "PLQ" & pdfname
For i = 1 To UBound(arNames)
If IsInArray(pdfname, arNames(i)) = True Then
ThisWorkbook.FollowHyperlink sPath & arNames(i)
End If
Next i
On Error GoTo 0
Exit Sub
OpenPdf_Error:
MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure OpenPdf"
End Sub
As far as you give the directory in which to "search" it is not a real search. Pretty much, everything needed could be just in one line:
ThisWorkbook.FollowHyperlink S:\PROFILE ORDERS\somePdf.pdf
the rest depends on how do you want to aproach it. The code below would throw an error, if there is no such file in the specified directory.
Sub OpenPdf()
On Error GoTo OpenPdf_Error
Dim pdfname As String
Const sPath = "C:\Users\gropc\Desktop\"
pdfname = Application.InputBox("Enter the pdf you are looking for")
pdfname = pdfname & ".pdf"
ThisWorkbook.FollowHyperlink sPath & pdfname
On Error GoTo 0
Exit Sub
OpenPdf_Error:
MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure OpenPdf"
End Sub
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.