Display Excel account username in a cell on open - vba

Working with Office 2013, I am trying to insert VBA code to automatically enter the employee name as it is displayed in the top right hand corner of any Office product into cell B2 upon them opening up the excel spreadsheet. The current code I am using is
Sub Auto_Open()
Range("B2").Value = " " & Application.UserName
End Sub
However, this just makes it display "Authorized User".
What am I doing wrong?

I poked around at this morning. I figured this information must be stored somewhere in the registry if it isn't accessible as part of the Excel object model. This makes sense, especially if this username is part of a corporate subscription.
The Registry Key
I did a search in the registry for how my username showed up in Excel, and this popped up.
The FriendlyName is exactly how my username shows up in Excel. So all we need now is a method to read this registry key's FriendlyName, and that should do it :)
Code
Here is some code that works for me based on the location of this key. It may be slightly different on your computer, so you may need to tweak this to find the FriendlyName
Private Function GetFriendlyName() As String
On Error GoTo ErrorHandler:
Const HKEY_CURRENT_USER = &H80000001
Const ComputerName As String = "."
Dim CPU As Object
Dim RegistryKeyPath As String
Dim RegistrySubKeys() As Variant
Dim RegistryValues() As Variant
Dim SubKeyName As Variant
Dim SubKeyValue As Variant
Dim KeyPath As String
GetFriendlyName = vbNullString
Set CPU = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & ComputerName & "\root\default:StdRegProv")
'Specify where to look
RegistryKeyPath = "Software\Microsoft\Office\" & Application.Version & "\Common\Identity\Identities"
'Enumerate the registry keys
CPU.EnumKey HKEY_CURRENT_USER, RegistryKeyPath, RegistrySubKeys
'Iterate each key in the identities folder
For Each SubKeyName In RegistrySubKeys
'Get each value in that folder
CPU.EnumValues HKEY_CURRENT_USER, RegistryKeyPath & "\" & SubKeyName, RegistryValues
'Go through each value, and find the Friendly Name
For Each SubKeyValue In RegistryValues
If SubKeyValue = "FriendlyName" Then
KeyPath = "HKEY_CURRENT_USER\" & RegistryKeyPath & "\" & SubKeyName & "\" & SubKeyValue
'Read the key
With CreateObject("Wscript.Shell")
GetFriendlyName = .RegRead(KeyPath)
End With
Exit Function
End If
Next
Next
CleanExit:
Exit Function
ErrorHandler:
'Handle errors here
Resume CleanExit
End Function
'Run this to see the output in the immediate window
Private Sub ExampleUsage()
Debug.Print "The friendly name is: " & GetFriendlyName
End Sub
Results
The friendly name is: Ryan A. Wildry

Try this:
Sub Auto_Open()
Dim Username As String
Dim path As String
Dim sourcefile As String
Dim objFso As FileSystemObject
Set objFso = CreateObject("Scripting.FileSystemObject")
If objFso.FileExists(path & " ~$" & sourcefile) Then
Username = Split(GetFileOwner(path, " ~$" & sourcefile), "\")(1)
Range("B2").Value = " " & Username
Else
MsgBox ("File not Found!")
End If
End Sub

Related

TXT Import Add Field Using Partial Filename

I am trying to import multiple .txt files from a directory into an Access table using VBA.
I have code that currently works that imports the data and moves the files to an archive directory.
What I need to do is add the first part of the filename as field in the table, namely the date.
The file format is MMDDYYYY_LbxReport.txt (ex 02082022_LbxReport.txt)
Here is the code that I have working, and I commented out what I tried to add to fix my problem:
Private Sub Command9_Click()
On Error GoTo bImportFiles_Click_Err
Dim objFS As Object, objFolder As Object
Dim objFiles As Object, objF1 As Object
'Dim dteEntry As Variant 'added this variant for use in UPDATE cmd
Dim strFolderPath As String
Set objFS = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFS.GetFolder("\\*****************\upload\SSDTestLBXa\")
Set objFiles = objFolder.files
For Each objF1 In objFiles
If Right(objF1.Name, 11) = "xReport.txt" Then 'LBX level report capture
'dteEntry = Left(objF1.Name, 8)
'dteEntry = Left(dteEntry, 2) & "/" & Mid(dteEntry, 3, 2) & "/" & Right(dteEntry, 4) 'added to reformat into standard date format
DoCmd.TransferText acImportDelim, "lbxlevelspecs", "lbxlevel", strFolderPath & objF1.Name, False
'CurrentDb.Execute "Update lbxlevel" & "Set EntryDate=" & dteEntry & "", [] 'getting syntax errors here
Name strFolderPath & objF1.Name As "\\**************\upload\SSDTestLBXa\Archive\" & objF1.Name 'Move the files to the archive folder
End If
Next
Set objF1 = Nothing
Set objFiles = Nothing
Set objFolder = Nothing
Set objFS = Nothing
'Call Site_level
MsgBox ctr & "All volumes imported", , "Volume Import"
bImportFiles_Click_Exit:
Exit Sub
bImportFiles_Click_Err:
MsgBox Err.Number & " " & Err.Description
Resume bImportFiles_Click_Exit
End Sub
I saw a similar thread for this question, but I can't get the syntax right, and the OP's code was very different from what I have that's working so far.
Any help would be greatly appreciated!
This is how you would construct the update statement:
Public Sub doit()
Dim dteEntry As Variant
dteEntry = Left("02142024_SomeName.txt", 8)
dteEntry = Left(dteEntry, 2) & "/" & Mid(dteEntry, 3, 2) & "/" & Right(dteEntry, 4) 'added to reformat into standard date format
CurrentDb.Execute "ALTER TABLE lbxlevel ADD EntryDate DATETIME"
CurrentDb.Execute "Update lbxlevel " & "Set EntryDate='" & dteEntry & "'"
End Sub
Because it needs apace before 'SET', and quotation marks around the date.
EDIT: I added the ALTER TABLE, this tests successfully on my side.

Save a copy of Database then email it to a shared email box

I have a script that saves a backup database (with a date stamp) to a shared drive.
Private Sub Command0_Click()
Dim fs As Object Dim oldPath As String, newPath As String
Dim CurrentDate As String
CurrentDate = Format(Now, "MMDDYY")
oldPath = "\\xxx\xxx Database" 'Folder file is located in
'newPath = "\\xxx\xxx\FINANCE\USERS\xxx\xxx Operations\xxx\xxx\" 'Folder to copy file to
newPath = "C:\Users\xxx\Documents\xxx\xxx" 'Folder to copy file to
Set fs = CreateObject("Scripting.FileSystemObject")
fs.CopyFile oldPath & "\" & "xxx Database Update v.1.6_be.accdb", newPath & "\" _
& "xxx Database Update v.1.6_be_" & CurrentDate & ".accdb"
Set fs = Nothing
MsgBox "Database Backed up", , "Backup Complete"
End Sub
This worked fine.
However I have now been asked to also send the database to a shared inbox email address.
Private Sub btnbrowse_click()
Dim filediag As FileDialog
Dim file As Variant
Set filediag = FileDialog(msofiledialogfilepicker)
filediag.allowmultiselect = False
If filediag.show Then
For Each file In filediag.selecteditems
Me.txtattachment = file
Next
End If
End Sub
Private Sub btnSend_Click()
Dim oApp As New Outlook.Application
Dim oEmail As Outlook.MailItem
Set oEmail = oApp.CreateItem(olMailItem)
oEmail.To = Me.txtto
oEmail.Subject = Me.txtsubject
oEmail.Body = Me.txtbody
If Len(Me.txtattachment) > 0 Then
oEmail.Attachments.Add Me.txtattachment.Value
End If
With oEmail
If Not IsNull(.To) And Not IsNull(.Subject) And Not IsNull(.Body) Then
.Send
MsgBox "Email Sent!"
Else
MsgBox "Please fill out the required fields."
End If
End With
End Sub
Please can somebody help me link the two scripts so that instead of using the FileDialog to choose the email attachment, I can use the path in the first query to select the attachment and the script will run both the save file and the email file commands at the same time.
It's just the filename, so it could be just passing the value from your script:
oEmail.Attachments.Add newPath & "\xxx Database Update v.1.6_be_" & CurrentDate & ".accdb"
If you want to just automatically send after the backup, make the email code a Sub that can be called in Backup button click procedure.
Sub SendEmail(strFile As String)
...
oEmail.Attachments.Add strFile
...
End Sub
Then calling the sub at end of the Backup button click:
SendEmail(newPath & "\xxx Database Update v.1.6_be_" & CurrentDate & ".accdb")
Many email systems reject emails with Access file as an attachment because of malicious code risk. However, a zipped Access file should pass security. Example code:
Dim strZip As String
strZip = CurrentProject.Path & "\Construction.zip"
'create empty zip folder
'found this on web, no idea what the Print line does but if it isn't there, this won't work
Open strZip For Output As #1
Print #1, "PK" & Chr$(5) & Chr$(6) & String(18, 0)
Close #1
'copy file into zip folder
Dim objApp As Object
Set objApp = CreateObject("Shell.Application")
'variable for source file doesn't seem to work in this line
'also double parens not in original example code but won't work without
objApp.NameSpace((strZip)).CopyHere CurrentProject.Path & "\Construction.accdb"
As noted in code comment, issue is passing source file via variable. Sorry, I never needed to solve.
Creating zip file code could be in the email procedure and then attach the zip file:
oEmail.Attachments.Add strZip
Then at the end of email procedure, can delete the zip file:
Kill strZip

VBA - Checking Folder/File exist in SharePoint

I wanted to copy a local file to sharepoint library using VBA by clicking an image. Right now seems like I'm unable to check for Folder & Files on SharePoint.
As every time I ran the code(by clicking an image in excel), it returns unable to find the file in SharePoint. And stops at returning the MsgBox Sorry there's no such Folder......
I tried mapping drive, it works perfectly fine, but not an options because end-user need to map the drive by themselves.
So now I'm looking to connecting to SharePoint using the link.
If I copy the SharePointLink to IE & Chrome using \, it works fine. But if I uses /, IE is unable to find the link.
UPDATE
If I uses \ after few tries, IE, will open up the file path in NetWork. Chrome will show the file path on chrome page. Why is this happening?????
The authentication is using windows authentication, so not an issue.
This is my code
Sub imgClicked()
Dim SharePointLib As String
Dim MyPath As String
Dim folderPath As String
Dim objNet As Object
Dim FSO As Object
Dim copyPath As String
Dim copyFilePath As String
folderPath = Application.ThisWorkbook.path
MyPath = Application.ThisWorkbook.FullName
SharePointLib = "//company.com/sites/MS/10%20Mg%20Review/"
' create new folder to store the file
copyPath = folderPath + "\copyPath\"
If Not FolderExists(copyPath) Then
FolderCreate (copyPath)
ElseIf Not FolderExists(SharePointLib) Then
MsgBox "Sorry there's no such folder. Folder Path: " & vbNewLine & vbNewLine & SharePointLib & ""
Exit Sub
End If
fileName = "hello.xlsm"
'Copy current excel file and save at the new folder created
ThisWorkbook.SaveCopyAs copyPath & fileName
MsgBox "Save Copy As: " + copyPath & filseName & vbNewLine & vbNewLine & "The file will be uploaded to this address: " + SharePointLib & fileName
' Check whether the file exist in the directory
' If exist error message
' else copy the file from copyPath then paste at the SharePoint directory
If Not Dir(SharePointLib & fileName, vbDirectory) = nbNullString Then
MsgBox "Sorry file already exist!"
Else
Call FileCopy(copyPath & fileName, SharePointLib & fileName)
MsgBox "File has being successfuly created in SharePoint!"
End If
Set FSO = CreateObject("scripting.filesystemobject")
If Right(copyPath, 1) = "\" Then
copyPath = Left(copyPath, Len(copyPath) - 1)
End If
If FSO.FolderExists(copyPath) = False Then
MsgBox copyPath & " doesn't exist"
Exit Sub
End If
FSO.DeleteFolder copyPath
MsgBox "Folder has being deleted successfully!"
End Sub
Function for checking if folder exists
Function FolderExists(ByVal path As String) As Boolean
FolderExists = False
Dim FSO As New FileSystemObject
If FSO.FolderExists(path) Then FolderExists = True
End Function
Function for creating Folder
Function FolderCreate(ByVal path As String) As Boolean
FolderCreate = True
Dim FSO As New FileSystemObject
try:
If FSO.FolderExists(path) Then
Exit Function
Else
On Error GoTo catch
FSO.CreateFolder path
Debug.Print "FolderCreate: " & vbTab & path
Exit Function
End If
catch:
MsgBox "A folder could not be created for the following path: " & path & ". Check the path name and try again."
FolderCreate = False
Exit Function
End Function
Any help and suggestions are appreciated. Let me know if more info is needed. Thanks in advance.
Ensure the WebClient service is running. You can start the WebClient service through code, or you could set the startup type to automatic.
With the WebClient service running, your folder/file tests will work as expected.
Edit: Additionally, if you map the sharepoint url to a drive letter, Windows will start the WebClient service.
Sub mapPath(str_drive as string, str_path as string)
If Not Len(str_drive) = 1 Then Exit Sub
Dim wso As Object
Set wso = CreateObject("WScript.Network")
wso.MapNetworkDrive str_drive & ":", str_path, False
End Sub

retrieve current path from file saved on server

How I can retrieve the current path of current db?
I've one AC07 program, to distribute it I save one copy on the intranet server, how to copy this program into our PC and then use it?
Always some people open the file directly on server.
When the file is open one form star automatically, in this form I put this code:
Private Sub Form_Load()
On Error GoTo ErrorHandler
Dim StrServer As String
StrServer = "\\itbgafs01\Comune\Dashboard\"
If GetDBPath() = StrServer Then
MsgBox "You can't open this file from server" & vbCrLf & _
"save one copy on you PC, and use those", vbCritical, "Dashboard.info"
Application.Quit
End If
Public Function GetDBPath() As String
Dim strFullPath As String
Dim I As Integer
strFullPath = CurrentDb().Name
For I = Len(strFullPath) To 1 Step -1
If Mid(strFullPath, I, 1) = "\" Then
GetDBPath = left(strFullPath, I)
Exit For
End If
Next
End Function
My problem is: some PC are mapped on drive H: the server directory then the path result is H:\Comune\Dashboard\ and not \\itbgafs01\\Dashboard\.
How I can retrieve the absolute path?
First I think to use more if like:
Private Sub Form_Load()
On Error GoTo ErrorHandler
Dim StrServer As String
Dim StrMaph As String
StrServer = "\\itbgafs01\Comune\Dashboard\"
StrMaph = "H:\Comune\Dashboard\"
MsgBox StrServer & vbCrLf & _
StrMaph & vbCrLf & _
GetDBPath()
If GetDBPath() = StrServer Or GetDBPath() = StrMaph Then
MsgBox "Non puoi aprire il file sul server" & vbCrLf & _
"copialo sul tuo pC ed avvia il programma da li", vbCritical, "Dashboard.info"
Application.Quit
End If
Is there another way to do it?
You can use the Scripting Runtime to get the UNC path of the drive then replace it in the currentDb.Name.
E.g.:
Sub blah()
Debug.Print GetUNCPath(CurrentDb.Name)
End Sub
Function GetUNCPath(path As String) As String
Dim fso As Object, shareName
Set fso = CreateObject("Scripting.FileSystemObject")
shareName = fso.GetDrive( _
fso.GetDriveName(path)).shareName
'sharename is empty if it wasn't a network mapped drive (e.g. local C: drive)
If shareName <> "" Then
GetUNCPath = shareName & Right(path, Len(path) - InStr(1, path, "\"))
Else
GetUNCPath = path
End If
End Function
Edit: alternatively you can use a call to the WinAPI to get the info: https://support.microsoft.com/en-us/kb/160529

Visual basic script not working on Outlook 2010 rule

I've been trying to find a script that saves attachments to a folder on our network from Outlook. I've finally got something working but it looks like it doesn't work on my 2nd system which happens to be Outlook 2010. I can't say for sure if it's because of this difference.
Code is:
Sub SaveAllAttachments(objItem As MailItem)
Dim objAttachments As Outlook.Attachments
Dim strName, strLocation As String
Dim dblCount, dblLoop As Double
strLocation = "C:\test\"
On Error GoTo ExitSub
If objItem.Class = olMail Then
Set objAttachments = objItem.Attachments
dblCount = objAttachments.Count
If dblCount <= 0 Then
GoTo 100
End If
For dblLoop = 1 To dblCount
strID = " from " & Format(Date, "mm-dd-yy") 'Append the Date
'strID = strID & " at " & Format(Time, "hh`mm AMPM") 'Append the Time
' These lines are going to retrieve the name of the
' attachment, attach the strID to it to insure it is
' a unique name, and then insure that the file
' extension is appended to the end of the file name.
strName = objAttachments.Item(dblLoop).Filename 'Get attachment name
strExt = Right$(strName, 4) 'Store file Extension
strName = Left$(strName, Len(strName) - 4) 'Remove file Extension
strName = strName & strID & strExt 'Reattach Extension
' Tell the script where to save it and
' what to call it
strName1 = strLocation & "PDF\" & strName 'Put it all together
strName2 = strLocation & "JPG\" & strName 'Put it all together
' Save the attachment as a file.
objAttachments.Item(dblLoop).SaveAsFile strName1
objAttachments.Item(dblLoop).SaveAsFile strName2
Next dblLoop
objItem.Delete
End If
100
ExitSub:
Set objAttachments = Nothing
Set objOutlook = Nothing
End Sub
It doesn't matter what Outlook version you are using at the moment. The code should work correcly.
Possible reasons why it doesn't work:
I'd suggest choosing another location for saving files. The C: drive requires admin privileges on latest OS.
The rule is not triggered.
An error in the script. Try to call the script manually from other VBA sub and see what happens under the hood. Do you get any errors in the code?