here is what I am trying to do:
The file is supposed to save itself according to the user's input and even if there is an input at all. Meaning, if a user has not made any inputs yet, the IF-Statement should return the first part (thats why UserName = ""). But if a user had previously already entered something, I want it to return the second part of the IF-Statement.
The original name of the file is 20210910_Besprechungsnotizen_00_ and if Jack is the first person to open that document and create a protocol, the name is supposed to be: 20210910_Besprechungsnotizen_00_Jack and only asking for Jack's Name. If Jack wants Steve to go over this document, then word should realize, Jack already saved this document (entered his initials or his name) and it will ask Steve which version this document is currently being on and add Steve behind Jack. Meaning:
20210910_Besprechungsnotizen_01_JackSteve while Steve only entered his name and 1.
I am a newbie & your help is much appreciated!
Here is my code:
Private Sub CommandButton3_Click()
Dim FilePath As String
Dim Filename As String
Dim MyDate As String
Dim UserName As String
If UserName = "" Then
FilePath = "//SRVDC\Arbeitsordner\Intern\Meetings\Entwürfe\"
MyDate = Format(Date, "YYYYMMDD")
Filename1 = "_Besprechungsnotizen_i_00_"
UserName = InputBox("Wer erstellt? (Name in Firmenkurzform)")
ActiveDocument.SaveAs2 FilePath & MyDate & Filename1 & UserName
Else
FilePath = "//SRVDC\Arbeitsordner\Intern\Meetings\Entwürfe\"
MyDate = Format(Date, "YYYYMMDD")
Filename1 = "_Besprechungsnotizen_i_0"
Filename2 = "_"
UserName = InputBox("Wer bearbeitet? (Name in Firmenkurzform)")
Version = InputBox("Welche Version? (in ganzen Zahlen)")
ActiveDocument.SaveAs2 FilePath & MyDate & Filename1 & Version & Filename2 & UserName
End If
End Sub
Try this:
Private Sub CommandButton3_Click()
Const FilePath As String = "//SRVDC\Arbeitsordner\Intern\Meetings\Entwürfe\"
Const OrigFileName As String = "20210910_Besprechungsnotizen_00_"
Dim Filename As String: Filename = "_Besprechungsnotizen_i_0"
Dim MyDate As String: MyDate = Format(Date, "YYYYMMDD")
Dim UserName As String
Dim Version As String
If Split(ActiveDocument.Name, ".")(0) = OrigFileName Then
'file has not been resaved
Else
'file has been saved before so extract data from filename
Dim nameElements As Variant
nameElements = Split(Split(ActiveDocument.Name, ".")(0), "_")
UserName = nameElements(UBound(nameElements))
Version = nameElements(UBound(nameElements) - 1)
End If
If UserName = "" Then
UserName = InputBox("Wer erstellt? (Name in Firmenkurzform)")
Version = "0_"
Else
Dim currentUser As String
currentUser = InputBox("Wer bearbeitet? (Name in Firmenkurzform)")
If currentUser = UserName Then
'you need to figure out what you want to do in this case
Else
'you also need to figure out what you want to do when you already have two names
UserName = UserName & currentUser
End If
'do you really need to prompt the user for the version number?
'couldn't you just increment the existing number, e.g.
'Version = Format$(Version + 1, "00")
Version = InputBox("Welche Version? (in ganzen Zahlen)") & "_"
End If
ActiveDocument.SaveAs2 FilePath & MyDate & Filename & Version & UserName
End Sub
Working with InputBox() can be a bit slow and tricky. Anyway, try printing whatever you have entered and see where in the code you are.
Sub TestMe()
Dim userName As String
Dim usedVersion As String
userName = InputBox("Enter username")
If userName = "" Then
Debug.Print "UserName is empty"
Else
Debug.Print "Username " & userName & " was entered."
Debug.Print "Asking for version now:"
usedVersion = InputBox("Welche Version? (in ganzen Zahlen)")
Debug.Print "Version "; usedVersion; " was entered"
End If
End Sub
This is how the debug looks like:
Related
I'm having a little trouble getting a filename using a wildcard.
I'm using a wildcard because the filename has a "version" in it so in this case "Test v*" could be "Test v1" or "Test v2" because of this I want it to pull the name of whatever version is currently on the desktop.
Here is a simplistic version of my code. if ran you get "Test v*" rather than the actual file name. Not sure what I'm missing but any help would be greatly appreciated
Dim Owner As String
Dim Cver As String
Dim FileName As String
Owner = Environ("USERNAME")
FileName = "C:\Users\" & Owner & "\Desktop\TEST v" & "*" & ".accdb"
Cver = Left(FileName, InStr(FileName, ".") - 1)
MsgBox "" & Mid(Cver, 7, 2) & ""
you are going to want to use Dir()
Here is my version of your code:
Sub getVersion()
Dim owner As String
Dim Cver As String
Dim fileName As String
Dim owner As String: owner = Environ("USERNAME")
Dim fileName As Variant: fileName = Dir("C:\Users\" & owner & "\Desktop\TEST v" & "*" & ".accdb", vbDirectory)
Cver = Left(fileName, InStr(fileName, ".") - 1)
MsgBox "" & Mid(Cver, 7, 2) & ""
End Sub
I am having 2 issues with my code.
First issue: I cant get it to save as the oriTitle when I am running the macro for the second time and answer with no to the question if I wanted to change the title. It will just be blank.
Second issue: I can only save it for 2 times. After that, I'll get running error. I'd like to keep going for at least 10 times.
Could someone help me with both issues? I have no clue what to do. Thanks in advance!
Private Sub CommandButton3_Click()
Const FilePath As String = "//SRVDC\Arbeitsordner\Intern\Meetings\Entwürfe\"
Const OrigFileName As String = "20210910_Besprechungsnotizen_00_"
Dim MyDate As String: MyDate = Format(Date, "YYYYMMDD")
Dim Title As String
Dim oriTitle As String: oriTitle = "Besprechungsnotizen"
Dim newTitle As String
Dim currentTitle As String
Dim User As String
Dim newUser As String
Dim currentUser As String
Dim Version As Integer
Dim newVersion As Integer
Dim currentVersion As Integer
If Split(ActiveDocument.Name, ".")(0) = OrigFileName Then
'file has not been resaved
Else
'file has been saved before so extract data from filename
Dim nameElements As Variant
nameElements = Split(Split(ActiveDocument.Name, ".")(0), "_")
User = nameElements(UBound(nameElements))
Version = nameElements(UBound(nameElements) - 1)
End If
If User = "" Then
User = InputBox("Wer erstellt? (Name in Firmenkurzform)")
newTitle = MsgBox("Anderer Titel?", vbQuestion + vbYesNo + vbDefaultButton2, "Titel")
If newTitle = vbYes Then
Title = InputBox("Wie soll der Titel sein?")
Else
Title = oriTitle
End If
Version = "0"
Else
currentUser = InputBox("Wer bearbeitet? (Name in Firmenkurzform)")
If currentUser = User Then
Else
User = User & "_" & currentUser
End If
newTitle = MsgBox("Neuer Titel?", vbQuestion + vbYesNo + vbDefaultButton2, "Titel")
If newTitle = vbYes Then
Title = InputBox("Wie soll der neue Titel sein?")
Else
End If
Version = MsgBox("Neue Version?", vbQuestion + vbYesNo + vbDefaultButton2, "Version")
If Version = vbYes Then
newVersion = currentVersion + 1
Version = newVersion
Else
Version = currentVersion
End If
End If
ActiveDocument.SaveAs2 FilePath & MyDate & "_" & Title & "_i_0" & Version & "_" & User
End Sub
The problem here is that you are simply not thinking anything through. You have also simply used the code given to you in a previous answer without first ensuring that you understand it.
NEVER use code you get from the internet without first working through it line by line and ensuring that you fully understand what each part of the code does. You can use the tools in the Visual Basic Editor to help with this. Place your cursor in a term you don't understand and press F2 to display the Object Browser, or F1 to access the online help.
I have added comments to the code to indicate your mistakes.
Private Sub CommandButton3_Click()
Const FilePath As String = "//SRVDC\Arbeitsordner\Intern\Meetings\Entwürfe\"
Const OrigFileName As String = "20210910_Besprechungsnotizen_00_"
Dim MyDate As String: MyDate = Format(Date, "YYYYMMDD")
Dim Title As String
Dim oriTitle As String: oriTitle = "Besprechungsnotizen"
Dim newTitle As String
Dim currentTitle As String
Dim User As String
Dim newUser As String
Dim currentUser As String
Dim Version As Integer
Dim newVersion As Integer
Dim currentVersion As Integer
If Split(ActiveDocument.Name, ".")(0) = OrigFileName Then
'file has not been resaved
Else
'file has been saved before so extract data from filename
Dim nameElements As Variant
nameElements = Split(Split(ActiveDocument.Name, ".")(0), "_")
User = nameElements(UBound(nameElements))
Version = nameElements(UBound(nameElements) - 1)
End If
If User = "" Then
User = InputBox("Wer erstellt? (Name in Firmenkurzform)")
'why are you using Title here when it is the variable used to save the document?
'you should use newTitle for the MsgBox return value
Title = MsgBox("Anderer Titel?", vbQuestion + vbYesNo + vbDefaultButton2, "Titel")
If Title = vbYes Then
'you should be using the Titlke variable here, not newTitle
newTitle = InputBox("Wie soll der Titel sein?")
'corect the prvious two lines and these next two can be deleted
Title = newTitle
'this sets newTitle to a blank string as you haven't assigned a value to currentTitle yet
newTitle = currentTitle
Else
Title = oriTitle
'this sets oriTitle to a blank string as you haven't assigned a value to currentTitle yet
oriTitle = currentTitle
End If
Version = "0"
Else
currentUser = InputBox("Wer bearbeitet? (Name in Firmenkurzform)")
If currentUser = User Then
Else
'if you use an underscore to separate the user names you will not be able to extract
'the version number
'you need to use a different character to separate the names and then use the Split
'function to return those names as an array
User = User & "_" & currentUser
End If
'see comments above
Title = MsgBox("Neuer Titel?", vbQuestion + vbYesNo + vbDefaultButton2, "Titel")
If Title = vbYes Then
newTitle = InputBox("Wie soll der neue Titel sein?")
Title = newTitle
newTitle = currentTitle
Else
Title = currentTitle
End If
'comments above also apply here. You should have used the newVersion variable for the MsgBox
Version = MsgBox("Neue Version?", vbQuestion + vbYesNo + vbDefaultButton2, "Version")
If Version = vbYes Then
newVersion = currentVersion + 1
Version = newVersion
Else
'you haven't assigned a value to currentVersion yet so it will set Version to zero
Version = currentVersion
End If
End If
ActiveDocument.SaveAs2 FilePath & MyDate & "_" & Title & "_i_0" & Version & "_" & User
End Sub
Thanks to another post and the main help of Timothy, I was able to finish my code. here's what I got in case somebody in the future is trying something similar.
And I even addded the option to save as PDF and decide if this is supposed to be a new version or not.
Here saving as word:
Private Sub CommandButton3_Click()
Const FilePath As String = "//SRVDC\Arbeitsordner\Intern\Meetings\Entwürfe\"
Const OrigFileName As String = "20210910_Besprechungsnotizen_00_"
Dim Title As String: Title = "Besprechungsnotizen"
Dim newTitle As String
Dim MyDate As String: MyDate = Format(Date, "YYYYMMDD")
Dim User As String
Dim Version As String
If Split(ActiveDocument.Name, ".")(0) = OrigFileName Then
'file has not been resaved
Else
'file has been saved before so extract data from filename
Dim nameElements As Variant
nameElements = Split(Split(ActiveDocument.Name, ".")(0), "_")
User = nameElements(UBound(nameElements))
Version = nameElements(UBound(nameElements) - 1)
Title = nameElements(UBound(nameElements) - 3)
End If
If User = "" Then
User = InputBox("Wer erstellt? (Name in Firmenkurzform)")
newTitle = MsgBox("Anderer Titel?", vbQuestion + vbYesNo + vbDefaultButton2, "Titel")
If newTitle = vbYes Then
Title = InputBox("Wie soll der Titel sein?")
Else
End If
Version = "0"
Else
Dim currentUser As String
currentUser = InputBox("Wer bearbeitet? (Name in Firmenkurzform)")
If currentUser = User Then
Else
User = User & currentUser
End If
Version = Format$(Version + 1, "0")
End If
ActiveDocument.SaveAs2 FilePath & MyDate & "_" & Title & "_i_0" & Version & "_" & User
End Sub
Here the PDF part
Private Sub CommandButton1_Click()
Const FilePath As String = "//SRVDC\Arbeitsordner\Intern\Meetings\Finale Versionen\"
Const OrigFileName As String = "20210910_Besprechungsnotizen_00_"
Dim Title As String: Title = "Besprechungsnotizen"
Dim newTitle As String
Dim MyDate As String: MyDate = Format(Date, "YYYYMMDD")
Dim User As String
Dim Version As String
If Split(ActiveDocument.Name, ".")(0) = OrigFileName Then
'file has not been resaved
Else
'file has been saved before so extract data from filename
Dim nameElements As Variant
nameElements = Split(Split(ActiveDocument.Name, ".")(0), "_")
User = nameElements(UBound(nameElements))
Version = nameElements(UBound(nameElements) - 1)
Title = nameElements(UBound(nameElements) - 3)
End If
If User = "" Then
User = InputBox("Wer erstellt? (Name in Firmenkurzform)")
newTitle = MsgBox("Anderer Titel?", vbQuestion + vbYesNo + vbDefaultButton2, "Titel")
If newTitle = vbYes Then
Title = InputBox("Wie soll der Titel sein?")
Else
End If
Version = "0"
Else
newVersion = MsgBox("Neue Version?", vbQuestion + vbYesNo + vbDefaultButton2, "Neue Version")
If newVersion = vbYes Then
Dim currentUser As String
currentUser = InputBox("Wer bearbeitet? (Name in Firmenkurzform)")
If currentUser = User Then
Else
User = User & currentUser
End If
Version = Format$(Version + 1)
Else
Version = Format$(Version)
End If
End If
ActiveDocument.ExportAsFixedFormat OutputFileName:=FilePath & _
MyDate & "_" & Title & "_i_0" & Version & "_" & User & ".pdf", _
ExportFormat:=wdExportFormatPDF, _
OpenAfterExport:=False, _
OptimizeFor:=wdExportOptimizeForPrint, _
Range:=wdExportAllDocument, _
IncludeDocProps:=True, _
CreateBookmarks:=wdExportCreateWordBookmarks, _
BitmapMissingFonts:=True
End Sub
Using MS Access VBA. Setup is as follows:
tblUsers contains UserID, UserName, UserSecurityLevel, UserEmail
tblStewards contains AreaID, AreaName, Stewards where Stewards is set to be a Combo Box from a Lookup Query "SELECT tblUsers.ID, tblUsers.UserName FROM tblUsers" and I allow multiple values (e.g., each area has multiple stewards); the Stewards field has a data type of short text
frmStewardRequest has Record Source tblStewards and is designed for a user to request that the area stewards add a new item; it contains cmbAreaName, txtStewards which autopopulates based on cmbAreaName with Control Source Stewards, some open text fields for supplying the requested item, and a btnSubmitRequest
for btnSubmitRequest, I have an On Click event that generates an email to the area stewards using this VBA code:
Dim strEmailTo As String
Dim strTxtBody As String
strEmailTo = DLookup("[UserEmail]", "tblUsers", "ID = " & Me.txtSteward)
strTxtBody = "I need a new item in " & Me.cmbAreaName & "..."
DoCmd.SendObject , , acFormatTXT, strEmailTo, , , "New Item Request", strTxtBody, False
There is a problem with getting the email addresses for the area stewards: it doesn't seem this is a string. How can I get the email addresses so this will send properly? (Less important question, is there a way to prevent the pop-up box to Accept the risk of sending this email?)
This is how I do it.
Option Compare Database
Option Explicit
' This database and all the code therein is © 1999-2002 Arvin Meyer arvinm#datastrat.com
' You are free to use this code and this database in an application
' as long as you do not publish it without the author's permission.
' Additionally, you are required to include this copyright notice in the application.
Private Sub Form_Open(Cancel As Integer)
On Error GoTo Err_OF
Dim db As Database
Dim i As Integer
Dim contr As Container
Dim strRptList As String
Dim strRptName As String
Dim Length As Integer
Set db = CurrentDb()
Set contr = db.Containers("Reports")
strRptList = ""
For i = 0 To contr.Documents.Count - 1
strRptName = contr.Documents(i).name
If strRptList <> "" Then strRptList = strRptList & "; "
Length = Len(strRptName)
strRptList = strRptList & strRptName
Next i
Me!lstRpt.RowSource = strRptList
Exit_OF:
Exit Sub
Err_OF:
MsgBox Err & " " & Error, , "Report Open"
Resume Exit_OF
End Sub
Private Sub cmdEmail_Click()
On Error GoTo Err_cmdEmail_Click
Dim strDocName As String
Dim strEmail As String
Dim strMailSubject As String
Dim strMsg As String
strDocName = Me.lstRpt
strEmail = Me.txtSelected & vbNullString
strMailSubject = Me.txtMailSubject & vbNullString
strMsg = Me.txtMsg & vbNullString & vbCrLf & vbCrLf & "Your Name" & _
vbCrLf & "MailTo:youremail#nowhere.com"
DoCmd.SendObject objecttype:=acSendReport, _
ObjectName:=strDocName, outputformat:=acFormatHTML, _
To:=strEmail, Subject:=strMailSubject, MessageText:=strMsg
Exit_cmdEmail_Click:
Exit Sub
Err_cmdEmail_Click:
MsgBox Err.Description
Resume Exit_cmdEmail_Click
End Sub
Private Sub Label15_Click()
Dim hplMail As String
hplMail = "#MailTo:email_senate#datastrat.com#"
Application.FollowHyperlink HyperlinkPart(hplMail, acAddress)
End Sub
Private Sub lstRpt_Click()
Me.cmdEmail.Enabled = True
End Sub
Private Sub lstMailTo_Click()
Dim varItem As Variant
Dim strList As String
With Me!lstMailTo
If .MultiSelect = 0 Then
Me!txtSelected = .Value
Else
For Each varItem In .ItemsSelected
strList = strList & .Column(0, varItem) & ";"
Next varItem
strList = Left$(strList, Len(strList) - 1)
Me!txtSelected = strList
End If
End With
End Sub
Table tblStewards Combo Box lookup query SELECT tblUsers.ID, tblUsers.UserName FROM tblUsers needs to be fixed since there is no ID but UserID
Have used the Split function to check for multiple Steward values and then get their email id using Dlookup
I prefer using MultiValued fields especially when lookup list is not huge (nothing wrong to use).
Dim strStewards As Variant
Dim i As Long
Dim strEmailTo As String
Dim strTxtBody As String
strStewards = Split(Me.txtSteward, ",")
For i = LBound(strStewards) To UBound(strStewards)
strEmailTo = strEmailTo & ";" & Nz(DLookup("[UserEmail]", "tblUsers", "UserID=" & strStewards(i)), "")
Next
strTxtBody = "I need a new item in " & Me.cmbAreaName & "..."
DoCmd.SendObject , , acFormatTXT, strEmailTo, , , "New Item Request", strTxtBody, False
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.
i have a variable String named fileName and another variable named finalDoc
i am trying to compare both but it is not working. the program does not go in the if condition
Dim fileName As String
fileName = objFile.Name
finalDoc = cellValue & "-" & Range(sheetNo).Value & ".pdf"
//The fileName and finalDoc are getting values as expected
If finalDoc = fileName Then
'MsgBox finalDoc & " " & fileName
End If
the if condition is not working. it only works if i hardcode the value in fileName like
fileName ="abc.pdf"
any suggestions, i think this is a type issue String etc. Any help would be appreciated.
Using VBA of Excel 2013
You can't compare a string using "=". You must use the StrComp command that will return an integer depending on the outcome.
More information can be found Here
But here is an example that returns a match when comparing ABC.pdf and abc.pdf:
Sub test1()
Dim fileName1 As String
Dim fileName2 As String
Dim TestComp As Integer
fileName1 = "abc.pdf"
fileName2 = "ABC.pdf"
TestComp = StrComp(fileName1, fileName2, vbTextCompare)
If TestComp = 0 Then
MsgBox ("Match!")
Else
MsgBox (fileName1 & " and " & fileName2 & " are No Match. Outcome is " & TestComp)
End If
End Sub
All you now need to do is adjust this code to suit your needs.
Basically:
Dim fileName As String
Dim TestComp As Integer
fileName = objFile.Name
finalDoc = cellValue & "-" & Range(sheetNo).Value & ".pdf"
TestComp = StrComp(fileName,finalDoc,vbTextCompare)
If TestComp = 0 Then
//Insert code to run for a correct match
Else
//Insert code to run for incorrect match
End If