Username and Password in VBS script to be used in VBA - vba

How can I pull my username and password from a vbs script and input that into my vba code.
I manually input my username and password into the below, however I am worried others may find my login credentials.
VBA code:
Public Property Let jiraUSER(Value As String): pjiraUSER = "username"
End Property
Public Property Let jiraPW(Value As String): pjiraPW = "password"
End Property
VBS:
'Input Excel File's Full Path
ExcelFilePath = "O:\Export.xlsm"
'Input Module/Macro name within the Excel File
MacroPath = "JIRARestAPIEngine.scriptGO"
'Create an instance of Excel
Set ExcelApp = CreateObject("Excel.Application")
'Do you want this Excel instance to be visible?
ExcelApp.Visible = True 'or "False"
'Prevent any App Launch Alerts (ie Update External Links)
ExcelApp.DisplayAlerts = False
'Open Excel File
Set wb = ExcelApp.Workbooks.Open(ExcelFilePath)
'Execute Macro Code
ExcelApp.Run MacroPath
'Save Excel File (if applicable)
wb.Save
'Reset Display Alerts Before Closing
ExcelApp.DisplayAlerts = True
'Close Excel File
wb.Close
'End instance of Excel
ExcelApp.Quit
'Leaves an onscreen message!
MsgBox "Your Automated Task successfully ran at " & TimeValue(Now), vbInformation
Thanks.

Related

VBA - Sharepoint Check-out and Check-in a non-excel file

Problem
Excel VBA offers means to CheckOut and CheckIn Excel workbooks as follows:
if workbooks.CanCheckOut(sFile) then
workbook.CheckOut(sFile)
set wb = workbooks.open(sFile)
'make changes
wb.CheckIn true, "Some comment", true
end if
However if I am trying to check out a text file (or any other for that matter), How do I do this?
I made a sharepoint library.
To check out/in a file:
Dim sp as stdSharepointSite
set sp = stdSharepointSite.Create("teams","http://teams/wholesale/Leicester", "myUser", "myPass")
if sp.CheckOutFile("http://teams/wholesale/Leicester/myFile.txt", false) then
'Can and have checked out
'Do stuff
if thereAreChanges then
'save file to sharepoint
'...
'check in changes
sp.CheckInFile("http://teams/wholesale/Leicester/myFile.txt", "Updated my file")
else
'Discard checkout
sp.CheckOutDiscard("http://teams/wholesale/Leicester/myFile.txt")
end if
else
'Cannot checkout...
end if

Macro stops at `ThisWorkbook.EnvelopeVisible = True`

I'm trying to automated the process by using VBs to auto run the macro without opening the Excel.
I have tested the Macro and it works fine if the workbook is opened. However, when I run the Macro through the VBs Script, the Maro stops at ThisWorkbook.EnvelopeVisible = True. Does anybody knows why?
My Macro
Sub sendEmail()
MsgBox "sendEmail Start!" 'Appears when run VBs
ThisWorkbook.EnvelopeVisible = True
MsgBox "EnvelopeVisible True!" 'did not appear when run VBs
With ThisWorkbook.Sheets("sheet1").MailEnvelope
MsgBox "MailEnvelope Prepare!"
.Introduction = "Message"
.Item.To = "To who it may concern"
.Item.Subject = ""
.Item.Send
MsgBox "MailEnvelope Send!"
End With
ThisWorkbook.EnvelopeVisible = False
MsgBox "sendEmail Done!"
End Sub
My VBs
Set objExcel = CreateObject("Excel.Application")
objExcel.Application.Run "'C:\Users\UserName\Desktop\Folder\Ver 6.xlsm'!AutoEmail.sendEmail"
objExcel.DisplayAlerts = False
objExcel.Application.Quit
Set objExcel = Nothing
I'm running the VBs to activate the Macro
You need to add following line to VBS:
objExcel.Visible = True
just after
Set objExcel = CreateObject("Excel.Application")
It is based on a simple clue that your issue description gave.
Excel Macro works if it is opened and run from Excel.
It halts if it is being run from the VBS
When I looked at the MSDN explanation for this property
https://msdn.microsoft.com/en-us/vba/excel-vba/articles/workbook-envelopevisible-property-excel
It says
True if the e-mail composition header and the envelope toolbar are both visible. Read/write Boolean .
So to make it work we need to make the parent object visible i.e. Excel.Application.

Open another workbook with vba that contains all the macros

Instead of having all the macro's stored in each workbook, we would like to have them stored in one global one. We tried using Personal.xlsb file, however every time excel crashes or system administrator forced restart with excel open it created personal.v.01 ....v.100 files, and they interfered with each other, got corrupted etc.. So instead we are trying to add a small macro to each excel workbook we make which then should open a global excel workbook with all the macros, however it does not open it(normal.xlsb), where is the problem? If I manually run it it works fine, it just does not autorun..
Option Explicit
Public Sub Workbook_Open()
Dim sFullName As String
Dim xlApp As Excel.Application
Dim wbReturn As Workbook
sFullName = "Z:\Dokumentstyring\normal.xlsb"
Set xlApp = GetObject(, "Excel.Application") 'need to do so to open it in same instance otherwise the global macros can not be called.
Set wbReturn = xlApp.Workbooks.Open(filename:=sFullName, ReadOnly:=True)
If wbReturn Is Nothing Then
MsgBox "Failed to open workbook, maybe z drive is down?"
Else
ThisWorkbook.Activate'Dont know how to pass object to modules, so instead activate it and in createbutton set wb= activeworkbook..
Application.Run ("normal.xlsb!CreateButtons")
End If
End Sub
Public Sub Workbook_BeforeClose(Cancel As Boolean)
Dim wb As Workbook
For Each wb In Application.Workbooks
If InStr(UCase(wb.Name), "PARTSLIST") > 0 And wb.Name <> ThisWorkbook.Name Then Exit Sub
Next wb
On Error Resume Next
Workbooks("normal.xlsb").Close
Workbooks("filter.xlsx").Close
End Sub
You create your addin, as just an empty workbook, holding nothing but the code
Like this
Then you add a reference to it, in the workbook that you wish to use, in VBA, like this. My Documents, is a folder on a network drive, not "my documents" local.
And then you can call like so.
So based on input from #Nathan_Sav and #Ralph I have come to a partly good solution:
I have called my addinn Normal and saved this on Z:Dokumenstyring\Normal.xlam
I then removed all the code in Thisworkbook of Normal:
Private Sub Workbook_Open()
Dim ExcelArgs As String
Dim arg As String
ExcelArgs = Environ("ExcelArgs")
'Call deleteMacros.deletePersonalFiles
'MsgBox ExcelArgs
If InStr(UCase(ExcelArgs), "CREO,") > 0 Then
Application.DisplayAlerts = False
If Len(ExcelArgs) > Len("CREO,") Then
arg = Split(ExcelArgs, ",")(1)
Call Creo.addNewPartToPartslist(arg)
End If
Application.DisplayAlerts = True
End If
If InStr(UCase(ExcelArgs), "DOKLIST,") > 0 Then
Application.DisplayAlerts = False
If Len(ExcelArgs) > Len("DOKLIST,") Then
arg = Split(ExcelArgs, ",")(1)
Call ProsjektListen.dbDumpDocOut(arg)
End If
Application.DisplayAlerts = True
End If
and put this in a new workbook called Z:Dokumenstyring\Creo.xlsm
I have so edited all my bat files(which previously were using personal.xlsb):
echo "Launch excel"
Set ExcelArgs=CREO,ADDPART
"C:\Program Files (x86)\Microsoft Office\OFFICE16\Excel.exe" /x /r "z:\Dokumentstyring\Creo.xlsm"
So when I run the bat file it adds a parameter to enviroment, start creo.xlsm, which then starts the addin which launch my userform.
So if I now want to update the look of that that userform I do this by modifying the Z:Dokumenstyring\NormalDebug.xlam, then i save a copy which i write over Z:Dokumenstyring\Normal.xlam and I also told every user to not copy the addin to the default location in excel but keep it in Z:Dokumenstyring\Normal.xlam.
My shapes in my excel sheets seems to work with just the macro name in the procedure, however there might be an conflict if two procedures have the same name, but located in different procedures. So I also altered this to
ws1.Shapes(tempName).OnAction = "Normal.xlam!Custom_Button_Click"
However every click starts a new instance of the addin, how to avoid this?

copy formatted text into access using vba

I need to save formatted text from Word in an Access Database.
So far I've managed to figure out how to store formatted text in an Access Field (Create a Memo Field in a Table and set the Text Format as Rich Text). Searching SO I have not yet come across a solution as to how to transport said text from word into Access.
I know that it is possible, because you can do it by simply copying and pasting the information if you are doing it manually.
My question, how can I copy formatted text from word into a field in a table using VBA?
Experimentally I created the following to test this. So far without success...
Sub GetComments()
'Imports Analyst Comments from Excel files als OLE Objects.
'---------------------------------
'Access Variables
Dim dbsFundDB As DAO.Database
Dim rsComments As DAO.Recordset
Set dbsFundDB = CurrentDb
Set rsComments = dbsFundDB.OpenRecordset("tblFunds")
'Word Variables
Dim doc As Word.Application
Dim dcmt As Word.Document
Dim sectn As Word.Section
Dim obCommentText As Object
Dim sAnalystText As String
'Open New Word File
Set doc = New Word.Application
doc.Visible = True
Set dcmt = doc.Documents.Open(sPathTemplate)
Set sectn = dcmt.Sections(1)
sectn.Range.Select
Selection.InsertFile FileName:="myfile.rtf", Range:="", _
ConfirmConversions:=False, Link:=False, Attachment:=False
sAnalystText = sectn.Range.Tables(1).cell(1, 1).Range.FormattedText
rsComments.AddNew
rsComments![Long Comment Exec] = sAnalystText
rsComments.Update
sectn.Range.Select
dcmt.Close savechanges:=False
doc.Quit
End Sub
UPDATE
I tried implementing the answer from Matt Hall. While the text is indeed copied to the database, it does not yet keep the formatting:
Here is my implementation as a simple test:
Option Explicit
Public Const sPathTemplate As String = "W:\L\BDTP\Products\FundResearchTool\Advisory.docx"
Option Compare Database
Sub GetComments()
'Imports Comments from word and save in DB
'Test soubroutine
'---------------------------------
'Word Variables
Dim obCommentText As Variant
Dim strSQL As String
obCommentText = GetWordContent(sPathTemplate)
strSQL = "insert into [tblText]([TestField]) values('" & obCommentText & "')"
DoCmd.RunSQL strSQL
MsgBox "Import Successful", vbInformation Or vbOKOnly
End Sub
Private Function GetWordContent(strFile As String) As Variant
' This function takes the path obtained to the MS-Word Document selected in
' the FileToOpen function and then uses that to open that MS-Word Document
' and retrieve its text contents
Dim objDoc As Word.Document
Set objDoc = GetObject(strFile)
GetWordContent = CVar(objDoc.Sections(1).Range.Text)
objDoc.Close
End Function
Here's a method that heavily references this.
Before you start make sure you have these (or your Access version's equivalent) references ticked in VBA editor > Tools > References:
Microsoft Word 15.0 Object Library
Microsoft Office 15.0 Object Library
Assuming you've set up a form with a command button to trigger this MS-Word import, put the following function and subroutine somewhere in that form's VBA module:
1) File Picker Function:
This will allow you to select the MS-Word Document you want to using the old familiar file dialogue window you see throughout Windows. Ultimately, all it does is save the file path and name of the file you've picked for use in in the subroutine described in (2)...
Private Function FileToOpen() As String
' This function will essentially allow you to browse to MS-Word document
' and then store the path of that file for use in the GetWordContent function
Dim fDialog As Office.FileDialog
Dim varFile As Variant
Set fDialog = Application.FileDialog(msoFileDialogFilePicker)
With fDialog
.AllowMultiSelect = False
.Title = "Select Word document to import"
.Filters.Clear
.Filters.Add "Word files", "*.doc?"
If _
.Show = True _
Then
For Each varFile In .SelectedItems
FileToOpen = varFile
Next
Else
FileToOpen = ""
End If
End With
End Function
2) Get Formatted Text Contents of MS-Word Document Subroutine:
This subroutine will use the file path and name of the MS-Word Document selected in the File Picker function (above) to open the MS-Word document, select all the text, copy it to the clipboard, paste it to a text box on an open form in Access and then close MS-Word...
Private Sub GetWordContent(strFile As String)
' This function takes the path obtained to the MS-Word Document selected in
' the FileToOpen function and then uses that to open that MS-Word Document
' and retrieve its text contents and paste them in to WordDocData textbox on
' the currently open form in Access
' Create an MS-Word Object:
Dim objDoc As Object
Set objDoc = CreateObject("Word.Application")
' Open the file selected in FileToOpen() and copy the contents to clipboard:
With objDoc
.Documents.Open strFile
.Visible = True
.Activate
.Selection.WholeStory
.Selection.Copy
End With
' Set the focus to the WordDocData textbox on the Access Form and paste clipboard:
Me.WordDocData.SetFocus
DoCmd.RunCommand acCmdPaste
Me.WordDocDataSrc = strFile
' Save record on the form:
If _
Me.Dirty _
Then
Me.Dirty = False
End If
' A bit hacky this bit. When you close MS-Word after copying a lot of data,
' you might get a message asking you if you if you want to keep the last item
' you copied. This essentially overwrites the clipboard that currently has
' the whole document stored, to just the first 5 characters, which should allow
' MS-Word to be closed here without a pop-up message to deal with:
With objDoc
.Selection.HomeKey Unit:=wdLine
.Selection.MoveRight Unit:=wdCharacter, Count:=5, Extend:=wdExtend
.Selection.Copy
.Documents.Close
.Quit
End With
Set objDoc = Nothing
End Sub
Your Command Button's On-click Event:
This subroutine should be run from your command button's on-click event. It essentially calls FileToOpen function and the GetWordContent subroutine in order for the user to select a MS-Word Document and then let the VBA copy and paste the formatted text from the MS-Word Document in to a rich text memo textbox on the open form in Access.
Note that this subroutine makes some assumptions, and refers to names of controls/tables/fields and whatnot that you might not have already setup. These assumptions are:
Your form's command button is called cmdGetWordData
Your Access database has a table called tblWordDump
Your form is bound to the table tblWordDump
tblWordDump has 2 memo text fields called WordDocDataSrc and WordDocData to store the imported file path/name and text contents respectively and both are added to your form
Private Sub cmdGetWordData_Click()
' This subroutine runs on your command button; it will call both the FileToOpen function and GetWordContent subroutine
' to retrieve the text contents of your chosen MS-Word Document.
' It will then store both the path the text contents of of your chosen MS-Word Document in 2 fields in a table in Access.
' NOTE: this code assumes that your Access database has:
' - a table called tblWordDump
' - a memo text field in this table called WordDocDataSrc to store the path of MS-Word file imported
' - a memo text field in this table called WordDocData with the TextFormat property set to "Rich Text",
' which will store the text and text formating of the MS-Word file imported
Dim strFile As String
Dim strWordContent As Variant
' Select file via File Dialogue
strFile = FileToOpen
' Conditionals when a file was or wasn't selected
If _
Len(strFile) > 0 _
Then
DoCmd.GoToRecord , , acNewRec
GetWordContent strFile
MsgBox "Import Successful", vbInformation Or vbOKOnly
Else
MsgBox "No File Selected", vbExclamation Or vbOKOnly
End If
End Sub
Here's an example Access file of this for you to poke about in.

How to open excel workbook which needs login in vb?

I created an excel1 which has a login function (I've the username and password):
Pic: showing login window. (but I can't post the pic here because I don't have 10 reputation...)
Now I have another excel2 which need to read some information from excel1, and I want this can be done by just click a button, so I use vb.
But how to sent username&password to excel1 and open excel1 in background(I don't want the open process showing on screen).
Thanks
Add more description of my "login" window:
I insert an VBA Userform as the login window, it includes:
1, username_box: user can input login name here
2, pw_box: user can input password here
3, login_button: if click this button, sub login_button_Click() will be triggered
4, quit_button: if click this button, login will be cancelled
Private Sub login_button_Click()
Dim login_flag As Boolean
login_flag = False
'there is a sheet "users" which recorded the username and its password
For r = 2 To 100 Step 1
If username_box.Text = Sheets("users").Cells(r, 1).Value And pw_box.Text = Sheets("users").Cells(r, 2).Value Then
login_flag = True
Application.Visible = True
login_window.Hide
pw_box = ""
End If
Next r
If login_flag = False Then
MsgBox "Input wrong"
pw_box = ""
End If
End Sub
a lot depends on how the login to excel1.
If you use Workbook_Open Event to call UserForm where user fills login details, you can disable them Application.EnableEvents = False, example:
Sub OpenWb()
Dim FilePath As String
Dim WbSource As Workbook
Dim WbDest As Workbook
Dim ActWindow As String
Set WbDest = ActiveWorkbook
Application.EnableEvents = False
FilePath = "C:\tmp\excel1.xlsm" 'excel with password
Set WbSource = Workbooks.Open(FilePath)
ActWindow = ActiveWorkbook.Name
ActiveWindow.Visible = False
WbDest.Sheets(1).Cells(1, 1) = WbSource.Sheets(2).Cells(2, 2)
Application.EnableEvents = True
Windows(ActWindow).Visible = True
WbSource.Close savechanges:=False
End Sub
If you want read some information so that user dont see you can set the visibility to false:
ActiveWindow.Visible = False
From what i understand your problem might be.
When you open a excel workbook as intance, the userform wont show up. If it is data transfer you talking about, then you can easily do it without triggering the workbook.open module.