Script fails with error code 80040E31 - sql-server

We have a VBScript that downloads chunks of data from an SAP Business Object database into so-called slices, which are basically .csv files. The script worked perfectly so far, I haven't really had to look into it at all. But the failure now is this:
The script file section this error refers to is the dbConn.Execute(strSQL) line in the below code (5th from below).
What I tried so far, was to add these commands but they don't seem to solve anything:
'dbConn.ConnectionTimeout = 100
'dbConn.CommandTimeout = 100
The script itself (not all of it, I'm not sure the rest is needed):
Sub subRunFilesInFolder(strFolder)
Dim FSO, objFolder, objFiles
Dim i, intTS, intTS_file_start, ts, tsKillBefore, TS_file_start, strModelName
Dim dbConn, RST, RST2, strSQL
Dim strVBSmodel
Dim blRunIt
'INIs
strModelName = "bo_vbs_runner_1.5 "
strConn = "DRIVER={SQL Server};SERVER=EUBASEURCIREP01;UID=ser_login;PWD=ser_login;DATABASE=ser"
strComputer = FunstrComputerName
strBORunner = "\\Eubaseurcirep01\reporting\DEVELOPMENT\BO\Automation\Models\BO_auto_run.xlsb"
'Sets
Set dbConn = CreateObject("ADODB.Connection")
Set RST = CreateObject("ADODB.RecordSet")
Set RST2 = CreateObject("ADODB.RecordSet")
Set WshShell = WScript.CreateObject("WScript.Shell")
Set FSO = Wscript.CreateObject("Scripting.FileSystemObject")
Set objFolder = FSO.GetFolder(strFolder)
Set objFiles = objFolder.Files
Set appExcel = CreateObject("Excel.Application")
'dbConn.ConnectionTimeout = 100
'dbConn.CommandTimeout = 100
strVBSmodel = strModelName & strComputer & " " & FunstrUserName & " " & funCurrProcessId & " " & FunGetProcessIDCurrentOfExcel(strComputer)
appExcel.Application.Visible = False
appExcel.Displayalerts = False
Set objBORunner = appExcel.Workbooks.Open(strBORunner)
dbConn.Open strConn
ts = FunGetServerNow(dbConn,RST)
tsKillBefore = DateAdd("N", -15, ts)
intTS = funTimeStampToInteger(FunGetServerNow(dbConn, RST))
'Get ReportDate
strSQL = "SELECT yyyymmdd FROM map.reportdate WHERE dtAct=cast(GETDATE() as DATE);"
RST.Open strSQL, dbConn
If RST.EOF Then
strReportDate="99991231"
Else
strReportDate=RST.fields(0).value
End If
RST.close
'Kill stucked excel and vbs processes
strSQL = "SELECT distinct * FROM [ser].[bo].[_log] WHERE [proc]='BO VBS' AND result_text='started' AND end_timestamp<" & funTimeStampToInteger(tsKillBefore) & _
" AND lower(model) like '% " & LCase(strComputer) & " %';"
RST.Open strSQL,dbConn
If RST.EOF Then 'Nothing to kill
Else
Do While Not RST.EOF
strOldVBS = split(RST.fields("model"), " ")(3)
strOldExcel = split(RST.fields("model"), " ")(4)
Call SubKillProcessIDOnstrComputer(strComputer, strOldVBS)
Call SubKillProcessIDOnstrComputer(strComputer, strOldExcel)
strSQL = "UPDATE [ser].[bo].[_log] SET result_text='stopped', end_timestamp='" & funTimeStampToInteger(FunGetServerNow(dbConn,RST2)) & "' " & _
"WHERE [proc]='BO VBS' AND result_text='started' AND model='" & RST.fields("model").value & "' AND parameters='" & _
RST.fields("parameters").value & "';"
dbConn.Execute(strSQL)
RST.MoveNext
Loop
End If
RST.close

To Decode 0x8004nnnn Errors
HResults with facility code 4 means the HResult contains OLE errors (0x0 =
to 0x1ff) while the rest of the range (0x200 onwards) is component =
specific errors so 20e from one component will have a different meaning =
to 20e from another component.
You are lucky as your component is telling you it's OLDB with it's error - TIMEOUT

Related

Select long text from SQL using Excel VBA ADO returns garbage characters [duplicate]

This question already has an answer here:
What are the limits for ADO data types?
(1 answer)
Closed 3 years ago.
I can't figure out how to retrieve long text (>8kb) from a SQL Server field using an ADODB connection through Excel VBA. My method returns a garbage string.
I can successfully upload a field with >8kb data length using a parameterized query as in the following code:
Public Sub TestLongParamUploadQuery()
Dim conn As ADODB.Connection
Dim cmd As ADODB.Command
Dim param As ADODB.Parameter
Dim rs As ADODB.Recordset
Query = "INSERT INTO MYTABLE ([Long_Text], [Table_Index]) VALUES (?, ?);"
Set conn = New ADODB.Connection
conn.ConnectionString = connStr
On Error GoTo connerror
conn.Open
Set cmd = New ADODB.Command
With cmd
.ActiveConnection = conn
.CommandText = Query
.CommandType = adCmdText
Set Pm = .CreateParameter("long_text", adLongVarWChar, adParamInput, 20000)
Pm.Value = Replace("THIS IS A REALLY LONG TEXT STRING " & Space(8000) & "THIS IS A REALLY LONG TEXT STRING", " ", ".")
.Parameters.Append Pm
Set Pm = .CreateParameter("table_index", adVarChar, adParamInput, 32)
Pm.Value = "MYFAKERECORD"
.Parameters.Append Pm
Set rs = .Execute
End With
connerror:
If Err.Number <> 0 Then
Msg = "Error # " & str(Err.Number) & " was generated by " _
& Err.Source & Chr(13) & "Error Line: " & Erl & Chr(13) & Err.Description
MsgBox Msg, , "Error", Err.HelpFile, Err.HelpContext
End If
conn.Close
End Sub
But when I attempt to retrieve the data via a SELECT statement, the data comes back garbled.
Public Sub TestLongParamDownloadQuery()
Dim conn As ADODB.Connection
Dim cmd As ADODB.Command
Dim param As ADODB.Parameter
Dim rs As ADODB.Recordset
Query = "SELECT * FROM MYTABLE WHERE Table_Index='MYFAKERECORD';"
Set conn = New ADODB.Connection
conn.ConnectionString = connStr
On Error GoTo connerror
conn.Open
Set cmd = New ADODB.Command
With cmd
.ActiveConnection = conn
.CommandText = Query
.CommandType = adCmdText
End With
Set rs = cmd.Execute()
Do Until rs.EOF = True
For i = 0 To rs.Fields.Count - 1
If Not IsNull(rs.Fields.Item(i)) Then
Debug.Print ("field '" & rs.Fields(i).Name & "' length: " & Len(rs.Fields.Item(i)) & "; value: '" & rs.Fields.Item(i) & "'")
End If
Next
rs.MoveNext
Loop
connerror:
If Err.Number <> 0 Then
Msg = "Error # " & str(Err.Number) & " was generated by " _
& Err.Source & Chr(13) & "Error Line: " & Erl & Chr(13) & Err.Description
MsgBox Msg, , "Error", Err.HelpFile, Err.HelpContext
End If
conn.Close
End Sub
The data is successfully making it into the database. I'm able to open and see it in SQL Server Management Studio.
However. The Debug.Print output from my download looks like the following
field 'Long_Text' length: 8067; value: ' MYFAKERECORD ? ?%0?? ?%0?? ? ? ? ? ?
'
field 'Table_Index' length: 12; value: 'MYFAKERECORD'
Note that the length appears to be correct. It's not merely an issue in printing in the immediate window of the Excel VBA IDE. When I write the data to an excel cell via the macro, the cell contains '``' after upload.
I've tried the upload with the parameter for Unicode adLongVarWChar and plaintext adLongVarChar. Both appear to place data correctly in the database. Both come back as broken text from the select statement.
What is the appropriate way to download and interrogate long text via adodb?
EDIT I did find this thread which notes a fundamental limitation that ADO cannot interpret nvarchar(max) type. The proposed solution of CAST'ing the variable to nvarchar(20000) will not work for me because the upward limit for CAST is 8000 characters. How can I transfer data from a field GREATER than 8kb to Excel VBA?
This answer was drawn from the post What are the limits for ADO data types?
The solution as is to:
Cast the desired fields as text.
Retrieve the actual data from the record set using string = rs.Fields(0).GetChunk(rs.Fields(0).ActualSize)
Incorporating into my code it looks like:
Public Sub TestLongParamDownloadQuery()
Dim conn As ADODB.Connection
Dim cmd As ADODB.Command
Dim param As ADODB.Parameter
Dim rs As ADODB.Recordset
Query = "SELECT * FROM MYTABLE WHERE Table_Index='MYFAKERECORD';"
Set conn = New ADODB.Connection
conn.ConnectionString = connStr
On Error GoTo connerror
conn.Open
Set cmd = New ADODB.Command
With cmd
.ActiveConnection = conn
.CommandText = Query
.CommandType = adCmdText
End With
Set rs = cmd.Execute()
Do Until rs.EOF = True
For i = 0 To rs.Fields.Count - 1
If Not IsNull(rs.Fields.Item(i)) Then
If rs.Fields.Item(i).Name = "Long_Text" Then
Debug.Print(rs.Fields(i).GetChunk(rs.Fields(i).ActualSize))
End If
Debug.Print ("field '" & rs.Fields(i).Name & "' length: " & Len(rs.Fields.Item(i)) & "; value: '" & rs.Fields.Item(i) & "'")
End If
Next
rs.MoveNext
Loop
connerror:
If Err.Number <> 0 Then
Msg = "Error # " & str(Err.Number) & " was generated by " _
& Err.Source & Chr(13) & "Error Line: " & Erl & Chr(13) & Err.Description
MsgBox Msg, , "Error", Err.HelpFile, Err.HelpContext
End If
conn.Close
End Sub

Stored procedure from VBA Excel not running

I'm calling from VBA a stored procedure from a PC and it is working okay. In another PC and different user it is not working. A single query though, it is working in both PCs.
I'm calling the stored procedure as follows:
Dim rst As New ADODB.Recordset
Dim ConnectionString As String
Dim StrQuery As String
' Connection string for accessing MS SQL database
ConnectionString = <Connection details>
' Opens connection to the database
cnn.Open ConnectionString
' Timeout error in seconds for executing the entire query; The stored procedure normally runs for around 20 min
cnn.CommandTimeout = 2400
' Process execution
StrQuery = "exec [00_Main] #date = '01/31/2018' "
rst.Open StrQuery, cnn
rst.Close
I'm guessing that I have an error message when executing the stored procedure, but I don't know how to capture it.
I tried the following, but I don't get anything as an output
' Process execution
StrQuery = "exec [00_Main] #date = '01/31/2018' "
rst.Open StrQuery, cnn
Debug.Print rst.Fields.Count
Debug.Print rst.RecordCount
Debug.Print rst
rst.Close
When I run the stored procedure in SQL Management studio I just get output messages as the stored procedure just updates tables. Like:
(29145907 rows affected)
(330527 rows affected)
I tried also adding Error Information following link here, but the process runs without giving me any error. Like:
' Process execution
DateSelection = Sheets("STB Check").Range("F1")
'StrQuery = "exec [00_Main] #date = '" & DateSelection & "' "
StrQuery = "exec [00_Main] #date = '01/31/2018' "
rst.Open StrQuery, cnn
Done:
rst.Close
Exit Sub
AdoError:
Dim errLoop As Error
Dim strError As String
i = 1
' Process
StrTmp = StrTmp & vbCrLf & "VB Error # " & Str(Err.Number)
StrTmp = StrTmp & vbCrLf & " Generated by " & Err.Source
StrTmp = StrTmp & vbCrLf & " Description " & Err.Description
' Enumerate Errors collection and display properties of
' each Error object.
Set Errs1 = cnn.Errors
For Each errLoop In Errs1
With errLoop
StrTmp = StrTmp & vbCrLf & "Error #" & i & ":"
StrTmp = StrTmp & vbCrLf & " ADO Error #" & .Number
StrTmp = StrTmp & vbCrLf & " Description " & .Description
StrTmp = StrTmp & vbCrLf & " Source " & .Source
i = i + 1
End With
Next
MsgBox StrTmp
' Clean up Gracefully
On Error Resume Next
GoTo Done
Any ideas?
Use proper parameterization, and treat dates as Date, not as strings.
Instead of running that straight off ADODB.Recordset, use an ADODB.Command; set the command text to just the name of the stored procedure, and add an ADODB.Parameter to its Parameters collection, providing the cell value (after validating that IsDate returns True for that cell value) - like on learn.microsoft.com:
Dim theDate As Date
theDate = Sheets("STB Check").Range("F1").Value
Dim cmd As ADODB.Command
Set cmd = New ADODB.Command
Set cmd.ActiveConnection = cnn
cmd.CommandType = adCmdStoredProc
cmd.CommandText = "[00_Main]"
Dim dateParam As ADODB.Parameter
Set dateParam = cmd.CreateParameter("date", adDate, adParamInput)
dateParam.Value = theDate
cmd.Parameters.Append dateParam
Dim results As ADODB.Recordset
Set results = cmd.Execute

Update Access front end through batch file?

Looking to see if there would be a way for users to update their MS Access db front end by clicking a button. The button would then trigger a batch file that would grab the file from a location on our server, and overwrite the current db on the users local PC. All done within one office, so network addresses would be all the same.
Location of file to copy: 10.0.0.0.5/Data/DB/Database.accdb
Location of file to overwrite: c:\DB\Database.accdb
Any ideas? Ideally I would love for someone to write a nice exe file that deletes the older version and installs the newer version, but can't write that kind of code.
Write a batch file to retrieve the newer version of the front end from it's source and copy it into the folder where the user's copy of the front end file lives. Add a line at the end of the batch file to launch msacess.exe with the filename of your front end program as a command line parameter.
The batch file can be located anywhere, but I recommend locating it in the folder where your application front end will reside.
Create a Windows shortcut to the batch file, which can be placed on the users' Desktop or anywhere else the user expects to launch the application.
Bonus points for dressing up the shortcut to the batch file by changing the icon: Right-click|Properties|Change icon... button.
A nice article on the topic can be found here:
Deploy and update a Microsoft Access application in a Citrix environment
It uses neither a bat, nor an exe, but a VBscript:
Option Explicit
' Launch script for PPT test/development/operation.
' Version 1.3.0
' 2013-09-15
' Cactus Data. Gustav Brock
Const DESKTOP = &H10
Const LOCALAPPDATA = &H1C
Dim objFSO
Dim objAppShell
Dim objDesktopFolder
Dim objLocalAppDataFolder
Dim objLocalFolder
Dim objRemoteFolder
Dim strLocalFolder
Dim strRemoteFolder
Dim strDesktopFolder
Dim strLocalAppDataFolder
Dim strLocalAppDataDsgFolder
Dim strLocalAppDataDsgPptFolder
Dim strDsgSubfolder
Dim strPptSubfolder
Dim strPptAppSubfolder
Dim strPptNcSuffix
Dim strAppName
Dim strAppSuffix
Dim strShortcutName
Dim strAppLocalPath
Dim strAppLocalBackPath
Dim strAppRemotePath
Dim strShortcutLocalPath
Dim strShortcutRemotePath
Dim strRegPath
Dim strRegKey
Dim strRegValue
Dim booNoColour
Dim varValue
' Adjustable parameters.
strDsgSubfolder = "DSG"
strPptSubfolder = "PPT"
strPPtNcSuffix = "NC"
' ---------------------------------------------------------------------------------
' Uncomment one folder name only:
'strPptAppSubfolder = "Development"
strPptAppSubfolder = "Operations"
'strPptAppSubfolder = "Test"
' ---------------------------------
' Indicate if the script is for the normal version (0) or the no-colour version (1):
booNoColour = 0
' ---------------------------------------------------------------------------------
strRemoteFolder = "K:\_Shared\Sales Planning\Environments\" & strPptAppSubfolder
If booNoColour = 1 Then
strAppSuffix = strPptNcSuffix
Else
strAppSuffix = ""
End If
strAppName = "SalesPlanningTool" & strAppSuffix & ".accdb"
If strPptAppSubfolder = "Operations" Then
If strAppSuffix = "" Then
strShortcutName = "RunPPT.lnk"
Else
strShortcutName = "RunPPT " & strAppSuffix & ".lnk"
End If
Else
If strAppSuffix = "" Then
strShortcutName = "RunPPT " & strPptAppSubfolder & ".lnk"
Else
strShortcutName = "RunPPT " & strAppSuffix & " " & strPptAppSubfolder & ".lnk"
End If
End If
' Enable simple error handling.
On Error Resume Next
' Find user's Desktop and AppData\Local folder.
Set objAppShell = CreateObject("Shell.Application")
Set objDesktopFolder = objAppShell.Namespace(DESKTOP)
strDesktopFolder = objDesktopFolder.Self.Path
Set objLocalAppDataFolder = objAppShell.Namespace(LOCALAPPDATA)
strLocalAppDataFolder = objLocalAppDataFolder.Self.Path
' Dynamic parameters.
strLocalAppDataDsgFolder = strLocalAppDataFolder & "\" & strDsgSubfolder
strLocalAppDataDsgPptFolder = strLocalAppDataDsgFolder & "\" & strPptSubfolder
strLocalFolder = strLocalAppDataDsgPptFolder & "\" & strPptAppSubfolder
strAppLocalPath = strLocalFolder & "\" & strAppName
strShortcutLocalPath = strDesktopFolder & "\" & strShortcutName
' Permanent parameters.
strAppRemotePath = strRemoteFolder & "\" & strAppName
strShortcutRemotePath = strRemoteFolder & "\" & strShortcutName
' Create the File System Object.
Set objFSO = CreateObject("Scripting.FileSystemObject")
If Not objFSO.FolderExists(strRemoteFolder) Then
Call ErrorHandler("No access to " & strRemoteFolder & ".")
Else
Set objRemoteFolder = objFSO.GetFolder(strRemoteFolder)
' If local folder does not exist, create the folder.
If Not objFSO.FolderExists(strLocalFolder) Then
If Not objFSO.FolderExists(strLocalAppDataDsgFolder) Then
Set objLocalFolder = objFSO.CreateFolder(strLocalAppDataDsgFolder)
If Not Err.Number = vbEmpty Then
Call ErrorHandler("Folder " & strLocalAppDataDsgFolder & " could not be created.")
End If
End If
If Not objFSO.FolderExists(strLocalAppDataDsgPPtFolder) Then
Set objLocalFolder = objFSO.CreateFolder(strLocalAppDataDsgPptFolder)
If Not Err.Number = vbEmpty Then
Call ErrorHandler("Folder " & strLocalAppDataDsgPptFolder & " could not be created.")
End If
End If
If Not objFSO.FolderExists(strLocalFolder) Then
Set objLocalFolder = objFSO.CreateFolder(strLocalFolder)
If Not Err.Number = vbEmpty Then
Call ErrorHandler("Folder " & strLocalFolder & " could not be created.")
End If
End If
End If
Set objLocalFolder = objFSO.GetFolder(strLocalFolder)
End If
If Not objFSO.FileExists(strAppRemotePath) Then
Call ErrorHandler("The application file:" & vbCrLf & strAppRemotePath & vbCrLF & "could not be found.")
Else
' Close a running PPT.
Call KillTask("PPT")
' Wait while TaskKill is running twice to close the instance(s) of PPT and PPT Background.
Call AwaitProcess("taskkill.exe")
Call KillTask("PPT Background")
' Wait while TaskKill is running twice to close the instance(s) of PPT and PPT Background.
Call AwaitProcess("taskkill.exe")
' Copy app to local folder.
If objFSO.FileExists(strAppLocalPath) Then
objFSO.DeleteFile(strAppLocalPath)
If Not Err.Number = 0 Then
Call ErrorHandler("The application file:" & vbCrLf & strAppName & vbCrLF & "can not be refreshed/updated. It may be in use.")
End If
End If
If objFSO.FileExists(strAppLocalPath) Then
Call ErrorHandler("The local application file:" & vbCrLf & strAppLocalPath & vbCrLF & "could not be replaced.")
Else
objFSO.CopyFile strAppRemotePath, strAppLocalPath
If Not Err.Number = vbEmpty Then
Call ErrorHandler("Application could not be copied to " & strLocalFolder & ".")
End If
' Create copy for PPT Background.
strAppLocalBackPath = Replace(Replace(strAppLocalPath, ".accdb", ".accbg"), "SalesPlanningTool", "SalesPlanningToolBack")
objFSO.CopyFile strAppLocalPath, strAppLocalBackPath
If Not Err.Number = vbEmpty Then
Call ErrorHandler("Background application could not be copied to " & strLocalFolder & ".")
End If
End If
' Copy shortcut.
objFSO.CopyFile strShortcutRemotePath, strShortcutLocalPath
If Not Err.Number = vbEmpty Then
Call ErrorHandler("Shortcut could not be copied to your Desktop.")
End If
End If
' Write Registry entries for Access security.
strRegKey = "HKEY_CURRENT_USER\Software\Microsoft\Office\14.0\Access\Security\"
strRegValue = "VBAWarnings"
strRegPath = strRegKey & strRegValue
varValue = 1
Call WriteRegistry(strRegPath, varValue,"REG_DWORD")
strRegKey = strRegKey & "Trusted Locations\LocationLocalAppData\"
strRegValue = "AllowSubfolders"
strRegPath = strRegKey & strRegValue
varValue = 1
Call WriteRegistry(strRegPath, varValue, "REG_DWORD")
strRegValue = "Date"
strRegPath = strRegKey & strRegValue
varValue = Now
varValue = FormatDateTime(varValue, vbShortDate) & " " & FormatDateTime(varValue, vbShortTime)
Call WriteRegistry(strRegPath, varValue, "REG_SZ")
strRegValue = "Description"
strRegPath = strRegKey & strRegValue
varValue = "Local AppData"
Call WriteRegistry(strRegPath, varValue, "REG_SZ")
strRegValue = "Path"
strRegPath = strRegKey & strRegValue
varValue = strLocalAppDataFolder & "\"
Call WriteRegistry(strRegPath, varValue, "REG_SZ")
' Run PPT.
If objFSO.FileExists(strAppLocalPath) Then
Call RunApp(strAppLocalPath, False)
Else
Call ErrorHandler("The local application file:" & vbCrLf & strAppLocalPath & vbCrLF & "could not be found.")
End If
Set objRemoteFolder = Nothing
Set objLocalFolder = Nothing
Set objLocalAppDataFolder = Nothing
Set objDesktopFolder = Nothing
Set objAppShell = Nothing
Set objFSO = Nothing
WScript.Quit
' Supporting subfunctions
' -----------------------
Sub RunApp(ByVal strFile, ByVal booBackground)
Dim objShell
Dim intWindowStyle
' Open as default foreground application.
intWindowStyle = 1
Set objShell = CreateObject("WScript.Shell")
objShell.Run Chr(34) & strFile & Chr(34), intWindowStyle, False
Set objShell = Nothing
End Sub
Sub KillTask(ByVal strWindowTitle)
Dim objShell
Set objShell = CreateObject("WScript.Shell")
objShell.Run "TaskKill.exe /FI ""WINDOWTITLE eq " & strWindowTitle & """", 7, False
Set objShell = Nothing
End Sub
Sub AwaitProcess(ByVal strProcess)
Dim objSvc
Dim strQuery
Dim colProcess
Dim intCount
Set objSvc = GetObject("winmgmts:root\cimv2")
strQuery = "select * from win32_process where name='" & strProcess & "'"
Do
Set colProcess = objSvc.Execquery(strQuery)
intCount = colProcess.Count
If intCount > 0 Then
WScript.Sleep 300
End If
Loop Until intCount = 0
Set colProcess = Nothing
Set objSvc = Nothing
End Sub
Sub WriteRegistry(ByVal strRegPath, ByVal varValue, ByVal strRegType)
' strRegType should be:
' "REG_SZ" for a string
' "REG_DWORD" for an integer
' "REG_BINARY" for a binary or boolean
' "REG_EXPAND_SZ" for an expandable string
Dim objShell
Set objShell = CreateObject("WScript.Shell")
Call objShell.RegWrite(strRegPath, varValue, strRegType)
Set objShell = Nothing
End Sub
Sub ErrorHandler(Byval strMessage)
Set objRemoteFolder = Nothing
Set objLocalFolder = Nothing
Set objLocalAppDataFolder = Nothing
Set objDesktopFolder = Nothing
Set objAppShell = Nothing
Set objFSO = Nothing
WScript.Echo strMessage
WScript.Quit
End Sub
You could probably convert it to PowerShell, which I would use today.
I use a vbscript for that purpose. I only update the path for the file due to be copied and then I sent an email to the users with a link to the script. The user clicks the link and the script is executed.
Copy the code below to a text file and save it as .vbs. Don't forget to set the path for the file due to be copied.
Option Explicit
Call Main()
Private Sub Main()
const folderFrom = "\\Somepath\Somefolder\" 'Folder: Must supply backslash
const fileName = "SomeFile.accdb" 'File name with extension
const overwrite = -1 'OverWrite = True
'Ask user to proceed
dim msg
msg = "The script will copy the file below to your desktop. " & vbNewLine & vbNewLine & _
String(75,"_") & vbNewLine & vbNewLine & _
"File: " & " " & " " & " " & " " & " " & " " & " '" & fileName & "' " & vbNewLine & _
"Folder: " & " " & " '" & folderFrom & "' " & vbNewLine & _
String(75,"_") & vbNewLine & vbNewLine & _
"Proceed?"
if MsgBox(msg, vbYesNo + vbQuestion, "FileCopy Confirmation") = vbNo then exit sub
on error resume next
dim filesys
set filesys = CreateObject("Scripting.FileSystemObject")
'File exists in folder?
if not filesys.FileExists(folderFrom & fileName) then
MsgBox "File not found. Task aborted. ", vbOKOnly + vbExclamation, "Attention:"
exit sub
end if
'User's desktop path
dim desktopPath
desktopPath = CreateObject("WScript.Shell").SpecialFolders("Desktop") & "\"
'Copy file
filesys.CopyFile folderFrom & fileName, desktopPath & fileName, overwrite
'Validate file copied
if filesys.FileExists(desktopPath & fileName) then
Msgbox "File copied successfully.", vbOKOnly + vbInformation, "Success!"
else
MsgBox "File could not be copied... ", vbOKOnly + vbExclamation, "Copy Failed..."
end if
End Sub
Suggestion:
You shouldn't overwrite the existing front-end database but instead you should consider versioning e.g. v2.0, v2.1, v2.2 etc. for better tracking.

Incorrect syntax near 'AvayaSBCCRT'

I'm really sorry to be asking and I'm sure it's extremely simple to answer but whenever I try to run the macro in excel below, I get the error message stated in the title:
Sub CallsMacro()
Dim ConData As ADODB.Connection
Dim rstData As ADODB.Recordset
Dim wsSheet As Worksheet
Dim strServer As String
Dim strDatabase As String
Dim strFrom As String
Dim strto As String
Dim intCount As Integer
Set wsSheet = ActiveWorkbook.Worksheets("Refresh")
With wsSheet
strServer = "TNS-CCR-02"
strDatabase = "AvayaSBCCRT"
strFrom = .Range("C$2")
strto = .Range("C$3")
End With
Set ConData = New ADODB.Connection
With ConData
.ConnectionString = "Provider=SQLOLEDB;Data Source=" & strServer & ";" & "Initial Catalog=" & ";" & "persist security info=true;" & "User Id=dashboard; Password=D4$hboard;"
.CommandTimeout = 1800
.Open
End With
''Create the recordset from the SQL query
Set rstData = New ADODB.Recordset
Set wsSheet = ActiveWorkbook.Worksheets("Calls")
With rstData
.ActiveConnection = ConData
.Source = "SELECT DISTINCT CAST(c.createdate AS date) as [Date]," & _
"CASE WHEN c.[CategoryID] = 1 then 'Outbound' WHEN c.[CategoryID] = 2 then 'Inbound' Else 'Internal' end as [Direction], c.cli as [Number], c.ddi, 'CallCentre' as [Queue], '' as [Queue Time], u.username as [Agent], cast((c.DestroyDate - c.CreateDate) as TIME) as [Duration], 'Connected' as [Status], c.callID as [Reference]" & _
"FROM [AvayaSBCCRT].[dbo].[tblAgentActivity] as a" & _
"JOIN [AvayaSBCCRT].[dbo].[tblCallList] as c on c.calllistid = a.calllistid" & _
"JOIN [AvayaSBCCRT].[dbo].[tblUsers] as u on u.userid = a.AgentID" & _
"WHERE c.createdate between '" & strFrom & "' and '" & strto & "'" & _
"AND a.[ActivityID] = 3 "
.CursorType = adOpenForwardOnly
.Open
End With
wsSheet.Activate
Dim Lastrow As Long
Lastrow = Range("A" & Rows.Count).end(xlUp).Row
Range("A2:J" & Lastrow).ClearContents
If rs.EOF = False Then wsSheet.Cells(2, 1).CopyFromRecordset rsData
rs.Close
Set rs = Nothing
Set cmd = Nothing
con.Close
Set con = Nothing
End Sub
I've looked high and low and cannot find the reason for it. Anybody have any ideas?
You're missing spaces from the end of the lines. Your SQL contains for example:
[tblAgentActivity] as aJOIN [AvayaSBCCRT].[dbo].[tblCallList]

If Then not working

I've searched a lot about this problem, but I haven't found anything specific to this case. I'm trying to run a script that grabs all hosts from AD, then checks each one for a specific file. Two txt files are created, one with and one without. The problem I'm having is that all host names are added to the 'without' file and the 'with' file is empty, but I know for a fact that both lists should have hosts listed. I know the loop is working because all the host names are listed, but it fails to apply the if/then check. I apologize for the crudity of my script, I'm VERY new to this. I would GREATLY appreciate any tips...
Const ADS_SCOPE_SUBTREE = 2
Dim cn
Set cn = CreateObject("ADODB.Connection")
cn.Provider = "ADsDSOObject"
cn.Open "Active Directory Provider"
Dim cmd
Set cmd = CreateObject("ADODB.Command")
Set cmd.ActiveConnection = cn
Dim ou
ou = "DC=mydomain,DC=COM"
cmd.CommandText = "SELECT name " & _
"FROM 'LDAP://" & ou & "' " & _
"WHERE objectClass='computer' " & _
"ORDER BY name"
cmd.Properties("Page Size") = 1000
cmd.Properties("Searchscope") = ADS_SCOPE_SUBTREE
Const ForAppending = 8
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
Dim yesFile
Set yesFile = fso.OpenTextFile("pcswithsw.txt", ForAppending, True)
Dim noFile
Set noFile = fso.OpenTextFile("pcswithoutsw.txt", ForAppending, True)
Dim rs
Set rs = cmd.Execute
strComputer = rs(0)
rs.MoveFirst
Do Until rs.EOF
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colFiles = objWMIService.ExecQuery("Select * From CIM_DataFile Where Name = 'C:\\somefile.exe'")
If colFiles.Count = 0 Then
noFile.WriteLine rs(0)
Else
yesFile.WriteLine rs(0)
End If
rs.MoveNext
Loop
yesFile.Close
noFile.Close
Set yesFile = Nothing
Set noFile = Nothing
Set fso = Nothing
Figured it out finally. I loaded the list of hosts into an array, then fed the array to the If/Then statement. It runs slowly, but the majority of the processing time is the script waiting for non-existent hosts to reply (need to clean up AD).
Const ADS_SCOPE_SUBTREE = 2
Const ForAppending = 8
Dim hostArray()
Dim cn
Set cn = CreateObject("ADODB.Connection")
cn.Provider = "ADsDSOObject"
cn.Open "Active Directory Provider"
Dim cmd
Set cmd = CreateObject("ADODB.Command")
Set cmd.ActiveConnection = cn
Dim ou
ou = "DC=mydomain,DC=COM"
cmd.CommandText = "SELECT name " & _
"FROM 'LDAP://" & ou & "' " & _
"WHERE objectClass='computer' " & _
"ORDER BY name"
cmd.Properties("Page Size") = 1000
cmd.Properties("Searchscope") = ADS_SCOPE_SUBTREE
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
Dim outFile
Set outFile = fso.OpenTextFile("computers.txt", ForAppending, True)
Dim yesFile
Set yesFile = fso.OpenTextFile("pcswithsw.txt", ForAppending, True)
Dim noFile
Set noFile = fso.OpenTextFile("pcswithoutsw.txt", ForAppending, True)
Dim j
j=0
Dim rs
Set rs = cmd.Execute
rs.MoveFirst
Do Until rs.EOF
REDIM PRESERVE hostArray(j)
for i = 0 to rs.EOF
hostArray(j)=rs(0)
outFile.WriteLine rs(0)
rs.MoveNext
i = i + 1
j = j + 1
next
Loop
For Each strComputer in hostArray
On Error Resume Next
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colFiles = objWMIService.ExecQuery("Select * From CIM_DataFile Where Name = 'C:\\folder\\subfolder\\file.ext'")
If colFiles.Count = 0 Then
noFile.WriteLine strComputer
Else
yesFile.WriteLine strComputer
End If
Next
yesFile.Close
noFile.Close
Set yesFile = Nothing
Set noFile = Nothing
Set fso = Nothing
msgbox("All done")

Resources