I created a copy button in an Access form to copy the Data in the fields that users enter so they can paste it in an internal system.
I created VBA code "on the click:
Private Sub Command6_Click()
On Error GoTo Err_cmdDuplicate_Click
DoCmd.RunCommand acCmdSelectRecord
DoCmd.RunCommand acCmdCopy
Exit_cmdDuplicate_Click:
Exit Sub
Err_cmdDuplicate_Click:
MsgBox Err.Description
Resume Exit_cmdDuplicate_Click
End Sub
I am having 2 problems:
it copies all the data with the headers but pastes it vertically rather than horizontally. I guess it needs to be formatted. I have to add since the code was grabbing everything in the form even the information that I didn't want. I created a query then a report based on the query then made the copy button with the code behind it.
this is the code
Private Sub cmdCopy_Click()
On Error GoTo Err_cmdDuplicate_Click
'Copies values from agent entered data fields into
'required format for TAS and copies to
'system clipboard.
'control name and type are as follows:
'CboTeam
'CboTax
'TboCallBack
'TboCaller
'TboBusName
'CboAuthType
'TboAuthID
'CboContact
'TboDetail
'TboBal
'TboDelqs
Application.Echo False
Me.PasteBox.Visible = True
Me!PasteBox.Value = _
"Team: " & Me!CboTeam & vbNewLine & _
"Tax Type: " & Me!CboTax & vbNewLine & _
"Phone: " & Me!TboCallBack & vbNewLine & _
"Caller: " & Me!TboCaller & vbNewLine & _
"Business Name: " & Me!TboBusnAME & vbNewLine & _
"Authentication Method: " & Me!CboAuthType & vbNewLine & _
"Authentication ID: " & Me!TboAuthID & vbNewLine & _
"Contact Reason: " & Me!CboContact & vbNewLine _
& vbNewLine & _
"Call Detail:" & vbNewLine & _
Me!TboDetail & vbNewLine _
& vbNewLine & _
"Balance: " & Me!TboBal & vbNewLine & _
"Delinquent Periods: " & Me!TboDelqs
Me.PasteBox.SetFocus
DoCmd.RunCommand acCmdCopy
Me.cmdcopy.SetFocus
Me.PasteBox.Visible = False
Application.Echo True
Exit_cmdDuplicate_Click:
Exit Sub
Application.Echo True
Err_cmdDuplicate_Click:
MsgBox Err.Description
Application.Echo True
Resume Exit_cmdDuplicate_Click
Application.Echo True
End Sub
In Windows 7, I've got a VBScript that creates an email in Outlook with a link to the file when you right-click in Windows Explorer. The script is run by creating a shortcut to it and adding it to %userprofile%\SendTo (which shows up in the Send to when you right-click the file). The goal is to be able to send a link to the file and the folder that contains it, rather than sending it as an attachment. It works fine except it always give a link directly to the file. How do I modify it so it also provides a link to the folder in the second line?
Const olMailItem = 0
Const olFolderInbox = 6
If WScript.Arguments.Count = 0 Then
WScript.Quit
End If
Set objWMIService = GetObject("winmgmts:\\.\root\cimv2")
Set colItems = objWMIService.ExecQuery _
("Select * From Win32_Process Where Name = 'outlook.exe'")
If colItems.Count = 0 Then
Set objOutlook = CreateObject("Outlook.Application")
Set objNamespace = objOutlook.GetNamespace("MAPI")
Set objFolder = objNamespace.GetDefaultFolder(olFolderInbox)
objFolder.Display
End If
strFile = WScript.Arguments.Item(0)
Set objOutlook = CreateObject("Outlook.Application")
Set objItem = objOutlook.CreateItem(olMailItem)
objItem.Subject = "Here is a link to a file..."
objItem.HTMLBody = "Link to the file: " & strFile & "<BR>Link to the folder: " & strFile & ""
objItem.Display
Might be a simple answer, but I haven't been able to figure it out. Any help would be appreciated!
The FileSystemObject object and it's GetParentFolderName method could help. Note that for any of methods used (in next script) hold: a method works only on the provided path string. It does not attempt to resolve the path, nor does it check for the existence of the specified path.
option explicit
Dim strFile, FSO, oFile
If WScript.Arguments.Count > 0 Then
strFile = WScript.Arguments.Item(0)
Else
strFile = "D:\Remote\bat\COCL\bu bu bu\somefile.ext"
End If
Set FSO = CreateObject("Scripting.FileSystemObject")
Wscript.Echo "FSO 'path' methods" & vbNewLine & "---------------------" _
& vbNewLine & "GetAbsolutePathName: " & FSO.GetAbsolutePathName( strFile) _
& vbNewLine & "GetParentFolderName: " & FSO.GetParentFolderName( strFile) _
& vbNewLine & "GetDriveName: " & FSO.GetDriveName( strFile) _
& vbNewLine & "GetBaseName: " & FSO.GetBaseName( strFile) _
& vbNewLine & "GetExtensionName: " & FSO.GetExtensionName( strFile) _
& vbNewLine & "GetFileName: " & FSO.GetFileName( strFile)
Set FSO = Nothing
Wscript.Quit
I have an array with a unknown number of elements.
I am trying to find out how can I insert all the array elements into the body of the e-mail that I'll send.
Is there a way I can reference all items of an array ( without knowing how many elements exist) ?
My code is below
Dim MyArray() As String
Dim Msg As Object
Dim item As Object
Set olApp = GetObject(, "Outlook.Application")
Set olNs = olApp.GetNamespace("MAPI")
Set olFldr = olNs.GetDefaultFolder(olFolderInbox)
Set olItms = olFldr.Items
olItms.Sort "Received", False 'False = Ascending = Older to newer
i = 0
For Each Msg In olItms
If Msg.Class = olMail Then
If InStr(1, Msg.Subject, "1401001LS") > 0 Then
ReDim Preserve MyArray(i)
If i = 0 Then
MyArray(i) = "From: " & Msg.Sender & vbNewLine & "Sent: " & Msg.SentOn & vbNewLine & "To: " & Msg.To & vbNewLine & "CC: " & Msg.CC & vbNewLine & "Subject: " & Msg.Subject & vbNewLine & vbNewLine & Msg.Body
End If
If i > 0 Then
MyArray(i) = "From: " & Msg.Sender & vbNewLine & "Sent: " & Msg.SentOn & vbNewLine & "To: " & Msg.To & vbNewLine & "CC: " & Msg.CC & vbNewLine & "Subject: " & Msg.Subject & vbNewLine & vbNewLine & Split(Msg.Body, "From: ")(0)
End If
i = i + 1
End If
End If
Next Msg
Unload Me
Done.Show
End Sub
you can loop through the elements in the array using the method below
Dim sContentsOfArray as string
Dim iCnt As Integer
For iCnt = 0 To UBound(MyArray) Step 1
'access the element at position iCnt and put it at the end of the string
sContentsOfArray = sContentsOfArray + MyArray (iCnt)
Next iCnt
Using VBScript, is there any way to allow for multiple simultaneous writes to a text file from multiple computers? I need to run a script from multiple computers at the same time. The script will perform a DEFRAG and save the results to a text file. After that, the script will read from the DEFRAG log file, pull the fragmentation percentage, and write it to another MASTER log file that is meant to contain these results from every computer across the enterprise. If I always only run the script from one computer at a time, then everything works find and dandy. However, once I use a distribution point to throw the script out to the enterprise, the script works perfectly up until the point where more than one computer attempts to access the MASTER log file at the same time. That's when I'm running into access denied errors and the like. Here's what I've got so far...
strDrivePreCheckStarted = (Year(Date) & "-" & AEZiR(Month(Date)) & "-" & AEZiR(Day(Date)) & " # " & AEZiR(Hour(Time)) & ":" & AEZiR(Minute(Time)) & ":" & AEZiR(Second(Time)))
a=("===================================================================================")
b=(" Script started on " & strDrivePreCheckStarted)
Set objWMIService = GetObject( "winmgmts:\\.\root\cimv2" )
Set colSettings = objWMIService.ExecQuery ( "Select * from Win32_ComputerSystem", , 48 )
For Each objComputer in colSettings
CompNam = objComputer.Name
If CompNam = "" Then
CompNam = "ComputerNameNotFound"
End If
CompMfr = replace(objComputer.Manufacturer,",","")
If CompMfr = "" Then
CompMfr = "ComputerMfrNotFound"
End If
CompMdl = objComputer.Model
If CompNam = "" Then
CompNam = "ComputerModelNotFound"
End If
Next
Set dClient = GetObject( "winmgmts://" & CompNam & "/root/ccm:SMS_Client" )
Set result = dClient.ExecMethod_("GetAssignedSite")
mClient = result.sSiteCode
If mClient = "OLD" Then
mClient = "SMS"
End If
If mClient = "NEW" Then
mClient = "SCCM"
End If
If mClient = "" Then
mClient = "UNKNOWN"
End If
c=(" Computer: " & "[" & mClient & "] " & CompNam & " (" & CompMfr & " " & CompMdl & ")")
Set FSO = CreateObject("Scripting.FileSystemObject")
Set wshShell = CreateObject("WScript.Shell")
Set objShell = WScript.CreateObject("WScript.Shell")
Set strWinDir = FSO.GetSpecialFolder(0)
Set strSys32 = FSO.GetSpecialFolder(1)
Set strTempDir = FSO.GetSpecialFolder(2)
strLogsDir = "\\fileserver\shared\logs\"
Const ForReading = 1, ForWriting = 2, ForAppending = 8
Const OverwriteExisting = False
If FSO.FileExists(strLogsDir & CompNam & ".TXT") Then
WScript.Quit
Else
If FSO.FileExists(strLogsDir & CompNam & "_CHKDSK.LOG") Then
WScript.Quit
Else
If FSO.FileExists(strLogsDir & CompNam & "_DEFRAG.LOG") Then
WScript.Quit
Else
strCHKDSKStarted = (Year(Date) & "-" & AEZiR(Month(Date)) & "-" & AEZiR(Day(Date)) & " # " & AEZiR(Hour(Time)) & ":" & AEZiR(Minute(Time)) & ":" & AEZiR(Second(Time)))
d=(" CHKDSK Started: " & strCHKDSKStarted)
If FSO.FileExists(strSys32 & "\chkdsk.exe") Then
strCHKDSKReturn = objShell.Run("%COMSPEC% /c chkdsk.exe C: > " & chr(34) & strLogsDir & CompNam & "_CHKDSK.LOG" & chr(34), 0, True)
End If
If FSO.FileExists(strLogsDir & CompNam & "_CHKDSK.LOG") Then
Set ChkDskLog = FSO.OpenTextFile(strLogsDir & CompNam & "_CHKDSK.LOG", ForReading, True)
Do While ChkDskLog.AtEndOfStream <> True
Curline = ChkDskLog.ReadLine
If InStr(Curline, "KB in bad sectors.") Then
Curline = Trim(Curline)
strKBpos = InStr(1, Curline, "KB")-2
strBadKB = Left(Curline, strKBpos)
strBadKB = Trim(strBadKB)
If strBadKB > 0 Then
ChkDskFail = "Failed"
e=(" " & strBadKB & "KB Of Bad Sectors Found In Used Space")
f=(" Drive has Failed Integrity Check")
Else
ChkDskFail = "Passed"
e=(" " & strBadKB & "KB Of Bad Sectors Found In Used Space")
f=(" Drive has Passed Integrity Check")
End If
End If
Loop
If strBadKB = "" Then
ChkDskFail = "Failed"
e=(" Check Disk Log Existed But Was Incomplete: " & Date & " # " & Time)
f=(" Drive has Failed Integrity Check")
End If
Else
ChkDskFail = "Passed"
e=(" No Bad Sectors Found in Used Space")
f=(" Drive has Passed Integrity Check")
End If
ChkDskLog.Close
strCHKDSKFinished = (Year(Date) & "-" & AEZiR(Month(Date)) & "-" & AEZiR(Day(Date)) & " # " & AEZiR(Hour(Time)) & ":" & AEZiR(Minute(Time)) & ":" & AEZiR(Second(Time)))
g=(" CHKDSK Finished: " & strCHKDSKFinished)
strDEFRAGStarted = (Year(Date) & "-" & AEZiR(Month(Date)) & "-" & AEZiR(Day(Date)) & " # " & AEZiR(Hour(Time)) & ":" & AEZiR(Minute(Time)) & ":" & AEZiR(Second(Time)))
h=(" DEFRAG Started: " & strDEFRAGStarted)
If FSO.FileExists(strSys32 & "\defrag.exe") Then
strDEFRAGReturn = objShell.Run("%COMSPEC% /c defrag.exe C: -a -v > " & chr(34) & strLogsDir & CompNam & "_DEFRAG.LOG" & chr(34), 0, True)
End If
If FSO.FileExists(strLogsDir & CompNam & "_DEFRAG.LOG") Then
Set DefragLog = FSO.OpenTextFile(strLogsDir & CompNam & "_DEFRAG.LOG", ForReading, True)
Do While DefragLog.AtEndOfStream <> True
CurLine = DefragLog.ReadLine
If InStr(CurLine, "Total fragmentation") Then
FragPosition = InStr(1,CurLine," %",1)-2
CurLine = CurLine
strFragAmount = Right(CurLine,4)
strFragAmount = Left(strFragAmount,2)
strFragAmount = Ltrim(strFragAmount)
End If
Loop
Else
DefragFail = "Failed"
i=(" Log File Could not be Located. Please try Again.")
j=(" Drive has Passed Defragmentation Check")
End If
If strFragAmount = "" Then
DefragFail = "Failed"
i=(" An Unknown Error has Occured. Please try Again.")
j=(" Run 'DEFRAG -v' from this machine manually.")
Else
If strFragAmount < 30 Then
DefragFail = "Passed"
i=(" Drive is " & strFragAmount & "% Fragmented")
j=(" Drive has Passed Defragmentation Check")
End If
If strFragAmount >= 30 Then
DefragFail = "Failed"
i=(" Drive is " & strFragAmount & "% Fragmented")
j=(" Drive has Failed Defragmentation Check")
End If
End If
DefragLog.Close
strDEFRAGFinished = (Year(Date) & "-" & AEZiR(Month(Date)) & "-" & AEZiR(Day(Date)) & " # " & AEZiR(Hour(Time)) & ":" & AEZiR(Minute(Time)) & ":" & AEZiR(Second(Time)))
k=(" DEFRAG Finished: " & strDEFRAGFinished)
strDrivePreCheckFinished = (Year(Date) & "-" & AEZiR(Month(Date)) & "-" & AEZiR(Day(Date)) & " # " & AEZiR(Hour(Time)) & ":" & AEZiR(Minute(Time)) & ":" & AEZiR(Second(Time)))
l=(" Script finished on " & strDRIVEPreCheckFinished)
m=("===================================================================================")
Set TXTLog = FSO.CreateTextFile(strLogsDir & CompNam & ".TXT", True)
TXTLog.WriteLine(strDrivePreCheckStarted & "," & mClient & "," & CompNam & "," & CompMfr & "," & CompMdl & "," & strCHKDSKStarted & "," & strBadKB & "KB" & "," & ChkDskFail & "," & strCHKDSKFinished & "," & strDEFRAGStarted & "," & strFragAmount & "%" & "," & DefragFail & "," & strDEFRAGFinished & "," & strDrivePreCheckFinished)
TXTLog.Close
If FSO.FileExists(strLogsDir & "_FDE.CSV") Then
Set CSVLog = FSO.OpenTextFile(strLogsDir & "_FDE.CSV", ForAppending, True)
CSVLog.WriteLine(strDrivePreCheckStarted & "," & mClient & "," & CompNam & "," & CompMfr & "," & CompMdl & "," & strCHKDSKStarted & "," & strBadKB & "KB" & "," & ChkDskFail & "," & strCHKDSKFinished & "," & strDEFRAGStarted & "," & strFragAmount & "%" & "," & DefragFail & "," & strDEFRAGFinished & "," & strDrivePreCheckFinished)
Else
Set CSVLog = FSO.CreateTextFile(strLogsDir & "_FDE.CSV", True)
CSVLog.WriteLine("Pre-Check Started,Management Client,Asset Tag,Computer Manufacturer,Computer Model,CHKDSK Started,CHKDSK Bad Sectors,CHKDSK Results,CHKDSK Finished,DEFRAG Started,DEFRAG Amount,DEFRAG Results,DEFRAG Finished,Pre-Check Finished")
CSVLog.WriteLine(strDrivePreCheckStarted & "," & mClient & "," & CompNam & "," & CompMfr & "," & CompMdl & "," & strCHKDSKStarted & "," & strBadKB & "KB" & "," & ChkDskFail & "," & strCHKDSKFinished & "," & strDEFRAGStarted & "," & strFragAmount & "%" & "," & DefragFail & "," & strDEFRAGFinished & "," & strDrivePreCheckFinished)
End If
CSVLog.Close
If FSO.FileExists(strLogsDir & "_FDE.LOG") Then
Set InstallLog = FSO.OpenTextFile(strLogsDir & "_FDE.LOG", ForAppending, True)
InstallLog.WriteLine(b)
InstallLog.WriteLine(c)
InstallLog.WriteLine(d)
InstallLog.WriteLine(e)
InstallLog.WriteLine(f)
InstallLog.WriteLine(g)
InstallLog.WriteLine(h)
InstallLog.WriteLine(i)
InstallLog.WriteLine(j)
InstallLog.WriteLine(k)
InstallLog.WriteLine(l)
InstallLog.WriteLine(m)
Else
Set InstallLog = FSO.CreateTextFile(strLogsDir & "_FDE.LOG", True)
InstallLog.WriteLine(a)
InstallLog.WriteLine(b)
InstallLog.WriteLine(c)
InstallLog.WriteLine(d)
InstallLog.WriteLine(e)
InstallLog.WriteLine(f)
InstallLog.WriteLine(g)
InstallLog.WriteLine(h)
InstallLog.WriteLine(i)
InstallLog.WriteLine(j)
InstallLog.WriteLine(k)
InstallLog.WriteLine(l)
InstallLog.WriteLine(m)
End If
InstallLog.Close
FSO.DeleteFile(strLogsDir & CompNam & "_CHKDSK.LOG")
FSO.DeleteFile(strLogsDir & CompNam & "_DEFRAG.LOG")
End If
End If
End If
Function AEZiR(plngValue)
Dim pstrValue
Dim plngChars
Dim i
pstrValue = CStr(plngValue)
plngChars = Len(pstrValue)
If plngChars < 2 Then
For i = 1 to plngChars Step -1
pstrValue = "0" & pstrValue
Next
End If
AEZiR = pstrValue
End Function
What am I missing? Is this task even possible with VBScript? Thank you in advance.
As neither VBScript, nor the FileSystemObject provide locking, someone/thing else has to do it:
a [scripting] language with proper file locks
a data store (DBMS) that allows simultaneous access
a programmer who uses a semaphore (e.g. a renamed file) to control the file access
In my opinion, the third option is the worst, because
the programmer has to do all the work and to take all
the risks/responsibilities. Using a database would solve
the problem of access control out of the box; using a
suitable language would allow a standard/non-hacking
solution.
But if you like to live in interesting times - that's
the code structure I would try to get away with:
While it make sense to continue (# of tries, timeout, successfully written)
rename FileIsFree.log to FileIsLocked.log
If success
open FileIsLocked.log
write to FileIsLocked.log
close FileIsLocked.log
rename FileIsLocked.log to FileIsFree.log
break/exit
End If
End While
If Not successfully written
Panic
End If
ADDED:
Some food for thought:
discussion
code
I hope you come to the conclusion, that using a DBMS is the better idea.
What is wrong with this script?
Option Explicit
Dim objRootDSE, strDNSDomain, adoConnection
Dim strBase, strFilter, strAttributes, strQuery, adoRecordset
Dim dtmStart, dtmEnd, strStart, strEnd
Dim strID, strFirst, strLast, strNTName
dtmEnd = Now()
dtmStart = DateAdd("d", -7, dtmEnd)
strStart = CStr(Year(dtmStart)) _
& Right("0" & CStr(Month(dtmStart)), 2) _
& Right("0" & CStr(Day(dtmStart)), 2) & "000000.0Z"
strEnd = CStr(Year(dtmEnd)) _
& Right("0" & CStr(Month(dtmEnd)), 2) _
& Right("0" & CStr(Day(dtmEnd)), 2) & "235959.0Z"
' Determine DNS domain name.
Set objRootDSE = GetObject("LDAP://RootDSE")
strDNSDomain = objRootDSE.Get("defaultNamingContext")
' Use ADO to search Active Directory.
Set adoConnection = CreateObject("ADODB.Connection")
adoConnection.Provider = "ADsDSOObject"
adoConnection.Open "Active Directory Provider"
Set adoRecordset = CreateObject("ADODB.Recordset")
adoRecordset.ActiveConnection = adoConnection
' Search entire domain.
strBase = "<LDAP://" & strDNSDomain & ">"
'For user accounts for people created in the last week
strFilter = "(&(objectCategory=person)(objectClass=user)" _
& "(whenCreated>=" & strStart & ")(whenCreated<=" & strEnd & "))"
' Comma delimited list of attribute values to retrieve.
strAttributes = "employeeID,sn,givenName,sAMAccountName"
' Construct the LDAP query.
strQuery = strBase & ";" & strFilter & ";" & strAttributes & ";subtree"
' Run the query.
adoRecordset.Source = strQuery
adoRecordset.Open
' Enumerate the resulting recordset.
Do Until adoRecordset.EOF
' Retrieve values.
strID = adoRecordset.Fields("employeeID").Value
strLast = adoRecordset.Fields("sn").Value
strFirst = adoRecordset.Fields("givenName").Value
strNTName = adoRecordset.Fields("sAMAccountName").Value
Wscript.Echo """" & strID & """,""" & strLast & """,""" & strFirst
& """,""" & strNTName & """"
adoRecordset.MoveNext
Loop
' Clean up.
adoRecordset.Close
adoConnection.Close
cscript //nologo test.vbs > users.csv
returns
(53, 1) Microsoft VBScript compilation error: Expected statement
You're missing an underscore line continuation at the end of the first line of this snippet:
Wscript.Echo """" & strID & """,""" & strLast & """,""" & strFirst
& """,""" & strNTName & """"
It should look like this:
Wscript.Echo """" & strID & """,""" & strLast & """,""" & strFirst _
& """,""" & strNTName & """"