VB ping macro - object required - vb.net

I know absolutely nothing about VB but I'm trying to compile a quick ping test macro within a word document to test some malware sandbox software. However, I keep getting the runtime 424 error.
I've done a bit of research but with 0 knowledge of VB, I've failed to identify a solution. The code is as follows.
Sub Ping()
' Ping Macro
If My.Computer.Network.Ping("192.168.1.10") Then
MsgBox ("Server pinged successfully.")
Else
MsgBox ("Ping request timed out.")
End If
End Sub
I'm clearly missing something here. I assumed the object would have been the message box but I was wrong. Anybody know what I'm missing here?
EDIT: Debug shows the first line being the issue.
If My.Computer.Network.Ping("192.168.1.10") Then
Thanks.

My.Computer.Network.Ping() is a VB.Net function and is not available in VBA.
From some time ago I have a function to get the ping time, this should get you going.
You probably need only the StatusCode = 0 check.
' strAddress = IP or name
Public Function PingTime(strAddress) As Long
Dim objPing As Object, objStatus As Object
' Init: Assume error
PingTime = -1
On Error Resume Next
Set objPing = GetObject("WinMgmts:{impersonationLevel=impersonate}").ExecQuery _
("SELECT * FROM Win32_PingStatus WHERE Address = '" & strAddress & "' ")
If Err.Number <> 0 Then
Exit Function
End If
For Each objStatus In objPing
If objStatus.StatusCode = 0 Then
PingTime = objStatus.Properties_("ResponseTime").Value
Exit For
End If
Next
Set objStatus = Nothing
Set objPing = Nothing
End Function

Related

AddIns.Add statement throwing an Internal Error 51

I am trying to install addins programmatically (more precisely, it is automated version update on Workbook_Open event) but I have run into an issue with the AddIns.Add method, which just "does not work". I copy the desired adding into C:\Users\[username]\Documents\Addins and then feed the full filepath to AddIns.Add, however the addin is not added, as evidenced by the subsequent statement failing (subscript out of range, the name of the supposedly added addin does not exist).
During the install attempt, the execution simply runs through the AddIns.Add without any issue (except the result) but on stepping through, I am getting Internal error (Error 51). I have tried a number of ways to work around that, add Application.Wait before and after the AddIns.Add to make sure it has sufficient time, putting it into a Do While Loop statement to attempt multiple executions, but to no avail.
AddIns.Add Filename:=sInstallPath & sFile
AddIns(sAddinFullName).Installed = True
Btw this worked until yesterday, when I did a couple codes updates but not even remotely close to this area. I think I had some issues with this in past because the statement was envelopped by Application.Wait (Now + TimeValue("0:00:01")), which I think resolved probably a similar issue but I cannot recall that any more.
Edit: Adding a broader part of the code - a function that does the installation proper and on success, returns True.
Function InstallAddin(sFullPath, sAddinName) As Boolean
Dim oAddin As Object
Dim bAdded As Boolean
Dim i As Integer
Do Until bAdded = True Or i = 10
For Each oAddin In AddIns
If oAddin.Name = sAddinName Then
bAdded = True
Exit For
End If
Next oAddin
If bAdded = False Then
'Application.Wait (Now + TimeValue("0:00:01"))
AddIns.Add Filename:=sFullPath, CopyFile:=False
Debug.Print "Attempt " & i
'Application.Wait (Now + TimeValue("0:00:01"))
End If
i = i + 1
Loop
If bAdded = True Then
'disable events to prevent recurrence - installing addin counts as opening its workbook
Application.EnableEvents = False
AddIns(sAddinName).Installed = True
Application.EnableEvents = True
InstallAddin = True
End If
End Function
sFullPath : "C:\Users\Eleshar\Documents\Addins\MyAddin - v.0.25.xlam"
sAddinName : "MyAddin - v.0.25"
The "MyAddin - v.0.25.xlam" file is present in the installation path.
There is a piece of code elsewhere, which ensures that a regular WB is open during this event.
Edit 2: The full functionality of the macro is:
On opening the file by a user, offering self-install.
On opening the file by a user, checking for previous installed versions, offering self-installation (after which it removes the old versions, including itself).
On Workbook_Open, checking a Sharepoint repository for any new versions, offering to install the newest one available and removing any older versions including itself.
Edit 3: So I found an interesting thing... AddIns.Add does not seem to work when executed from the code (the addin does not get listed in Developer > Addins). However when I type the same exact statement into the immediate window during the execution, it works and then the addin can get installed...
Since you do not show all your used code, please try the next one. I am using it to auto install the add-ins I design:
Private Sub Workbook_Open()
Dim Name As String, tmp As Boolean, n As Boolean, Merk As String
Name = ThisWorkbook.BuiltinDocumentProperties(1) '(1)
On Error Resume Next
tmp = AddIns(Name).Installed
If Err.Number <> 0 Then
Err.Clear: On Error GoTo 0
If Workbooks.Count = 0 Then n = True
If n Then
Workbooks.Add
Merk = ActiveWorkbook.Name
End If
AddIns.Add FileName:=ThisWorkbook.FullName
AddIns(Name).Installed = True
If n Then Workbooks(Merk).Close False
End If
On Error GoTo 0
End Sub
'(1) it represents the Add-inn title. It can be set programmatically or manual in Properties - Details - Title. When add-in is not open!
So I did not really figure out the issue with AddIns.Add, however I worked around that but having the macro directly edit the Excel registry keys to install the add in.
Sub AddinInstall(sAddinName As String, ByVal sFullPath As String)
Dim oShell As Object: Set oShell = CreateObject("WScript.Shell")
Dim i As Integer: i = 0
Dim iIndex As Integer
Dim sRegKey As String: sRegKey = "HKEY_CURRENT_USER\SOFTWARE\Microsoft\Office\16.0\Excel\Options\OPEN"
Dim sSZ As String
sFullPath = ChrW(34) & sFullPath & ChrW(34)
On Error Resume Next
Do 'loop through registry keys (non-existent key results in error, so errors must be disabled) to find if lower version is installed
i = i + 1
sSZ = ""
sSZ = oShell.RegRead(sRegKey & CStr(i))
If Len(sSZ) > 0 Then
If sSZ Like "*" & sAddinName & "*" Then
Debug.Print sSZ
iIndex = i 'get number at the end of registry key name
End If
End If
Loop Until Len(sSZ) = 0
If iIndex > 0 Then 'previous version installed - overwrite
oShell.RegWrite sRegKey & CStr(iIndex), sFullPath, "REG_SZ"
Else 'previous version not found, create new registry key
oShell.RegWrite sRegKey & CStr(i), sFullPath, "REG_SZ"
End If
On Error GoTo 0
End Sub

What is the proper way to use ErrHandler and Resume Next

This is a project I inherited. I noticed that sometimes it doesn't log errors.
This routine raises an error so that it can log it along with the rest of the message.
But it never returns to the error point and actually logs the error.
I can see what it is supposed to do, but I can't see how to get it to work.
Public Sub PostErrorToLog(lngErrID As Long, strContext As String, Optional strEvent As String)
On Error GoTo ErrHandler:
Dim strErrEvent As String
Dim rst As New ADODB.Recordset
Dim pass As Integer
pass = 0
'Capture event description by triggering the error.
Err.Raise lngErrID ' It gets to here, then jumps
'Use AddNew because SQL may be added into strEvent, causing objSQL.RunADO() to fail.
Set rst = objSQL.GetRST("PostErrorToLog()", "[System Log]", , , adCmdTable)
rst.AddNew ' Never gets here.
rst![UID] = strCurrUID
rst![ErrorID] = lngErrID
rst![Source] = strContext
rst![Event] = ConcatenateStrings(strErrEvent, strEvent, " ")
rst.Update
rst.Close
FlushLog "Error"
Exit Sub
ErrHandler:
strErrEvent = Err.Description
pass = pass + 1
If pass > 2 Then ' Seems like pass is always going to be 1
Resume Next
End If ' It gets to here and exits the routine.
End Sub

Custom Outlook Macro only runs in VBA editor

I've created a Macro based on a blog post that only successfully runs in the VBA editor. When I run it from Outlook itself, nothing happens. Maybe you can see something obvious that I'm missing.
Pressed Alt+F11 to open the editor.
Named the module and pasted in the code.
Compiled and run. The e-mail in question opened in HTML-format as expected.
Closed the editor and added the button to the toolbar I wanted. Nothing happens.
Returned to the VBA editor and run the code. It works as expected.
Closed and re-opened Outlook to try the button again. Nothing happens.
Here's the code, with a screenshot of the code in the editor to follow.
Sub ReplyInHtmlFormat()
Dim olSel As Selection
Dim oMail As MailItem
Dim oReply As MailItem
Set olSel = Application.ActiveExplorer.Selection
Set oMail = olSel.Item(1)
If oMail.BodyFormat = olFormatPlain Or olFormatRichText Or olFormatUnspecified Then
oMail.BodyFormat = olFormatHTML
oMail.Save
End If
Set oReply = oMail.Reply
oReply.Display
Set olSel = Nothing
Set oMail = Nothing
Set oReply = Nothing
End Sub
You may want to check the macro permissions to make sure it is allowed to run. I hope that helps! ;-)
Try to add MsgBox statement outside of any If statement and you will be able to understand whether it is actually running or not when you click a button added to the toolbar.
Also, I'd recommend adding an error-handling routine to the function:
Public Sub OnErrorDemo()
On Error GoTo ErrorHandler ' Enable error-handling routine.
Dim x, y, z As Integer
x = 50
y = 0
z = x / y ' Divide by ZERO Error Raises
ErrorHandler: ' Error-handling routine.
Select Case Err.Number ' Evaluate error number.
Case 10 ' Divide by zero error
MsgBox ("You attempted to divide by zero!")
Case Else
MsgBox "UNKNOWN ERROR - Error# " & Err.Number & " : " & Err.Description
End Select
Resume Next
End Sub
So, you will be aware of any issues if any.

Download file using VBA for Mac Word 2016

I am trying to update a template for Word 2016 for Mac.
In the prior code, I was able to run MacScript() command to run an AppleScript that in turn ran a shell script.
It appears the only way now to run such a script is to use AppleScriptTask, which requires that the script exists already in Application Scripts folder, which presents problems when I'm trying to distribute this to other (non-savvy) users.
I'm trying to figure out alternative ways of doing this, but after weeks of research, I am still stumped.
The scripts I'm running do various things, but the most important right now is to download updated versions of the template from a website. I use ActiveX on the Windows side to do this, but can't do that on Mac.
Can anyone suggest any alternative approaches for Mac Word 2016, using VBA (only preferably)?
Thank you!
Try this:
ActiveDocument.FollowHyperlink "http://yoursite.com/yourpackage.zip"
Below is what I did to accomplish this. I set a timer to wait on the download, since it's being done outside of VBA.
Function Download(Path As String) As String
On Error GoTo Handler
Dim User, UserPath, dlFile, base_dest, final_dest, FName As String
Dim Timer As Boolean
Timer = False
Dim timeout As Variant
timeout = Now + TimeValue("00:00:10")
User = Environ("USER")
UserPath = "/Users/" & User & "/Downloads/"
base_dest = "/Users/" & User & [move/path/]
final_dest = base_dest & FName
ActiveDocument.FollowHyperlink Address:=Path
If Dir(final_dest) <> "" Then
Kill final_dest
End If
Timer = True
ReTry:
If Dir(dlFile) <> "" Then
FileCopy dlFile, final_dest
Kill dlFile
Download = final_dest
Exit Function
End If
Handler:
If Err.Number = 53 And Timer = False Then
Resume Next
ElseIf Err.Number = 53 And Timer = True Then
If Now > timeout Then
MsgBox "There is a problem downloading the file. Please check your internet connection."
End
Else
Resume ReTry
End If
Else
MsgBox Err.Number & vbNewLine & Err.Description
End
End If
End Function

VBA On.Time() Background Check in Combination with regular Usage

I am currently experiencing an Issue with the On.Time() Command.
The Ontime offsetvalue is set to 00:00:10 checking if Files are open. (Sort of a realtime checker).
Sub MacroAutoRun1()
Dim RunTime1 As Date
RunTime1 = Now + TimeValue("00:10:00")
Application.OnTime RunTime1, "MacroAutoRun1"
If IsFileOpen("H:\Operations_Front_Office\Organisation Helpdesk & Renseignement\Test\1\Statistik.xlsm") Then
Interface.Interface_Statistik_Open_Val.Caption = "File in use"
Else
Interface.Interface_Statistik_Open_Val.Caption = "File currently not used"
End If
If IsFileOpen("H:\Operations_Front_Office\Organisation Helpdesk & Renseignement\Test\1\Timesheet.xlsm") Then
Interface.Interface_Timesheet_Open_Val.Caption = "File in use"
Else
Interface.Interface_Timesheet_Open_Val.Caption = "File currently not used"
End If
If IsFileOpen("H:\Operations_Front_Office\Organisation Helpdesk & Renseignement\Test\1\Datasheet_Roulement_Final_Original.xlsm") Then
Interface.Interface_Roulement_Open_Val.Caption = "File in use"
Else
Interface.Interface_Roulement_Open_Val.Caption = "File currently not used"
End If
IsFileOpen is a created function as per below:
Function IsFileOpen(FileName As String)
Dim iFilenum As Long
Dim iErr As Long
On Error Resume Next
iFilenum = FreeFile()
Open FileName For Input Lock Read As #iFilenum
Close iFilenum
iErr = Err
On Error GoTo 0
Select Case iErr
Case 0: IsFileOpen = False
Case 70: IsFileOpen = True
Case Else: Error iErr
End Select
End Function
My Problem now is that while doing the check it seems other Procedures are not able to be completed such as:
If DateDfrHDSKMALADIE = 0 Then
Set FoundHDSKMaladie = Sheets("Congé + Maladie").Columns(1).Find(What:=Maladie1HDSKtxt, After:=Sheets("Congé + Maladie").Cells(1, 1))
X = FoundHDSKMaladie.Row
Y = FoundHDSKMaladie.Column + HDSKMALADIENumb
Sheets("Congé + Maladie").Cells(X, Y) = "M"
Then the FoundHDSKMaladie returns "Nothing" and it seems to me that the Find Method is not even applied.
Have you heard of such an issue? I would like to keep the search open in the Background (peferably), if that would not work I will then just revert to stopping the Timer when the Page is left and reactivate it when the User returns to the page.
Thanks in advance for your help.
I'm not sure why the method you are using are interuppting the other procedures, but I have used a similar things in the past using a workbook exists function. As the files that you are checking appear to be workbooks I'd suggest checking if using this function rather than the IsFileOpen function solves the issue. I beleive I saw this method in a excel/vba dummies book.
The string for the function would be "Statistik.xlsm" for example.
Function WorkbookExists(ByVal BookToCheck As String) As Boolean
Dim Path As String
On Error GoTo Find_Err
Path = Workbooks(BookToCheck).Saved
On Error GoTo 0
WorkbookExists = True
Exit Function
Find_Err:
WorkbookExists = False
End Function