Finding what is different from VB(MSVisualStudio 2005) and VBA(Excel) - visual-studio

I found code online for something I wanted to do.
As usual, I fired it up in Visual Studio and it works no problem.
The problem occurs in that, when I try to port it over to Excel, it ceases to work.
As I understand, VBA is a watered down version of VB. (Based on reading this article:
Difference between Visual Basic 6.0 and VBA)
Therefore, how to I find out what is lost between going between the two programming environments?
To give a bit more detail:
I wrote a program in Visual Studio that sends me an email when I press a button.
I then tried to port it into Excel as a Macro, but that didn't work.
EDIT: Adeed additional problem information
Here is what I have in Visual Studio
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
CDO_Mail_Small_Text()
End Sub
Sub CDO_Mail_Small_Text()
Dim iMsg As Object
Dim iConf As Object
Dim strbody As String
Dim Flds As Object
iMsg = CreateObject("CDO.Message")
iConf = CreateObject("CDO.Configuration")
iConf.Load(-1) ' CDO Source Defaults
Flds = iConf.Fields
With Flds
.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") _
= "morgan"
.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
.Update()
End With
strbody = "Hi there" & vbNewLine & vbNewLine & _
"This is line 1" & vbNewLine & _
"This is line 2" & vbNewLine & _
"This is line 3" & vbNewLine & _
"This is line 4"
With iMsg
.Configuration = iConf
.To = "Jeremiah.Tantongco#Powerex.com"
.CC = ""
.BCC = ""
.From = """Ron"" <ron#something.nl>"
.Subject = "Important message"
.TextBody = strbody
.Send()
End With
End Sub
End Class
Here is what I have running in Excel:
Sub Button1_Click()
CDO_Mail_Small_Text
End Sub
Sub CDO_Mail_Small_Text()
Dim iMsg As Object
Dim iConf As Object
Dim strbody As String
Dim Flds As Object
iMsg = CreateObject("CDO.Message")
iConf = CreateObject("CDO.Configuration")
iConf.Load (-1)
Flds = iConf.Fields
With Flds
.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") _
= "morgan"
.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
.Update
End With
strbody = "Hi there" & vbNewLine & vbNewLine & _
"This is line 1" & vbNewLine & _
"This is line 2" & vbNewLine & _
"This is line 3" & vbNewLine & _
"This is line 4"
With iMsg
.Configuration = iConf
.To = "Jeremiah.Tantongco#Powerex.com"
.CC = ""
.BCC = ""
.From = """Ron"" <ron#something.nl>"
.Subject = "Important message"
.TextBody = strbody
.Send
End With
End Sub
The not working is a:
"Run-time error '91':
Object variable or With block variable not set"
When I debug it takes me to the following line:
"iMsg = CreateObject("CDO.Message")"
Cheers,
-Jeremiah Tantongco

VBA is a compile-on-the-fly version of Classic VB. I always thought of it as sorta halfway between Full VB 6.0 and vb script. The key is you only have access to the basic VB 6.0 libraries and other COM libraries. Because many good com libraries are almost always available (like Scripting, ADO 2.6, the Office libraries like Excel and Word, etc.) this was actually very powerful.
However this is not .NET, and you have no access to .NET libraries whatsoever. When you say Visual Studio, do you mean Visual Studio 6.0? If you're copying code from VS.NET to Excel, that has no chance of working. But if you're copying code from VS6 (or earlier) to Excel VBA, you should be able to get that working. You probably just need to reference a library you were referencing in VS. We would need more information and of course the error.

In VB6/VBA you need to use the SET statement when working with objects
Set iMsg = CreateObject("CDO.Message")
Set iConf = CreateObject("CDO.Configuration")

Can't attest to the differences in code, but the following link has great examples of sending email in VBA. Might help you figure out what is going wrong.
http://www.rondebruin.nl/sendmail.htm

Related

Attaching workbook to email

I have the below code and it will open the email with the relevant details however the workbook is not attaching itself - cannot see why (being a newbie!)
Also is there a way of attaching a signature to the email? I'm using the newest version of the MS applications so not sure if this has any issues
Sub Email_workbook()
Dim OutApp As Object
Dim OutMail As Object
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
On Error Resume Next
With OutMail
.to = "pknight#xxxx.com"
.CC = ""
.BCC = ""
.Subject = "Daily UK Orders Report"
.Body = "Good afternoon, " & vbNewLine & vbNewLine & _
"Please see the attached report for today's UK orders" & vbNewLine & _
"Kind regards"
.Attachments.Add ActiveWorkbook.Daily_UK_Orders_Report.xlsm
.display
End With
On Error GoTo 0
Set OutMail = Nothing
Set OutApp = Nothing
End Sub
Thanks for your help
Phill

How to get the filepath and extension from drag and drop? BVS

I want to be able to send an attachment file just by dropping it on a script.
I've found this one that sends the file (it works for me):
Set fso=CreateObject("Scripting.FileSystemObject")
strSMTP="smtp.gmail.com"
strSubject="mail#gmail.com"
strSubject2="Attachment file"
strBody="-"
strAttach="FILEPATH"
If fso.FileExists(strAttach) then
Set iMsg = CreateObject("CDO.Message")
Set iConf = CreateObject("CDO.Configuration")
iConf.Load -1 ' CDO Source Defaults
Set Flds = iConf.Fields
With Flds
.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = strSMTP
.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 465
.Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1
.Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = "mail#gmail.com"
.Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "password"
.Item("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = 1
.Update
End With
With iMsg
Set .Configuration = iConf
.To = "mail2#gmail.com"
.CC = ""
.BCC = ""
.From = "mail1#gmail.com"
.Subject = strAttach
.TextBody = strBody
.AddAttachment strAttach
.Send
End With
Set iMsg = Nothing
Set iConf = Nothing
Else
MsgBox "The specified attachment does not exist"
End if
What I need is a modification to this script that allows me to change the 6th line strAttach="FILEPATH" with the path and the extension of the file that im dropping on it and then execute the "send mail script".
Found this two links related to my question, but I don't know how to use them, hope these can help you too.
How to get the fully qualified path for a file in VBScript?
http://vba-tutorial.com/parsing-a-file-string-into-path-filename-and-extension/
The first one just shows the filepath and the extension on a new window, but i need it to be overwritten on the 6th line.
Could someone help me? im not a programmer, just want to be able to send the files to my own mail because i need to print them later on another computer.
Sorry for my english. Im not a native speaker. Thanks in advance!
Use Arguments Property (WScript Object):
The Arguments property contains the WshArguments object (a
collection of arguments). Use a zero-based index to retrieve
individual arguments from this collection.
Set fso=CreateObject("Scripting.FileSystemObject")
strSMTP="smtp.gmail.com"
strSubject="mail#gmail.com"
strSubject2="Attachment file"
strBody="-"
''''''''''''''''''''''''''''''''''' strAttach="FILEPATH"
Set objArgs = WScript.Arguments
For ii = 0 to objArgs.Count - 1
SendMyMail fso.GetAbsolutePathName(CStr( objArgs( ii)))
Next
Sub SendMyMail( ByVal strAttach)
If fso.FileExists(strAttach) then
Set iMsg = CreateObject("CDO.Message")
Set iConf = CreateObject("CDO.Configuration")
iConf.Load -1 ' CDO Source Defaults
Set Flds = iConf.Fields
With Flds
.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = strSMTP
.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 465
.Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1
.Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = "mail#gmail.com"
.Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "password"
.Item("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = 1
.Update
End With
With iMsg
Set .Configuration = iConf
.To = "mail2#gmail.com"
.CC = ""
.BCC = ""
.From = "mail1#gmail.com"
.Subject = strAttach
.TextBody = strBody
.AddAttachment strAttach
.Send
End With
Set iMsg = Nothing
Set iConf = Nothing
Else
MsgBox strAttach & vbCrLf & "The specified attachment does not exist"
End if
End Sub
Should work
using file(s) drag&drop as well as
using SendTo… from right-click menu (see shell:sendto: Customize the Send To Menu in Windows 10, 8, 7, or Vista).
Please check Paul Sadowski's article Sending email with CDO to simplify your code.

VBA windows to mac

I made a code on my Windows PC, have multiple macro's/VBA's but made the file for somebody with an Mac.
not sure where to start with adjusting code, but has anyone a clue how the following problems are caused, this will help me with finding a solution.. I probably used windows specific components..
if somebody can push me in the right direction, it would be great.. Have found a few topics:
http://www.vbaexpress.com/forum/archive/index.php/t-12976.html
and this one probably has the solution for my PDF problem:
Excel VBA code to work on Mac, Create PDF Function
Problem 1: colomnwidth doesn't work:
End With
Columns("A:A").EntireColumn.AutoFit
Columns("A:A").ColumnWidth = 26
Columns("C:H").Select
Selection.ColumnWidth = 4.5
Columns("J:L").Select
Selection.ColumnWidth = 11.5
Columns("I:I").Select
Selection.ColumnWidth = 16.25
Columns("B:B").ColumnWidth = 11.5
Columns("J:L").Select
Selection.ColumnWidth = 10.25
Columns("I:I").EntireColumn.AutoFit
Button to make PDF gives "Could not Create PDF"
Sub SaveConcept()
Dim ws As Worksheet
Dim strPath As String
Dim myFile As Variant
Dim strFile As String
On Error GoTo errHandler
Range("N8:N9").Select
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 5287936
.TintAndShade = 0
.PatternTintAndShade = 0
End With
ActiveSheet.PageSetup.Orientation = xlLandscape
Set ws = ActiveSheet
strFile = Range("J15") _
& Format(Now(), " dd-mm-yyyy") _
& Format(" Concept") _
& ".pdf"
strFile = ThisWorkbook.Path & "\" & strFile
myFile = Application.GetSaveAsFilename _
(InitialFileName:=strFile, _
FileFilter:="PDF Files (*.pdf), *.pdf", _
Title:="Select Folder and FileName to save")
If myFile <> "False" Then
ActiveSheet.Range("L1", _
ActiveSheet.Range("L1").End(xlDown).End(xlDown).End(xlDown).End(xlToLeft).End(xlToLeft).End(xlToLeft).End(xlDown)).ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=myFile, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=True
End If
exitHandler:
Exit Sub
errHandler:
MsgBox "Could not create PDF file"
Resume exitHandler
End Sub
thanks
There shouldn't be an issue with the first part+ as it's nothing specific to windows, for the second part - you're using "\" as the path separator for the PDF file, on a Mac this is typically ":"
To make the code compatible for both, use the application value instead:
strFile = ThisWorkbook.Path & Application.PathSeparator & strFile
+note: this was OP code at time of answer

Transfering windows-specific macro to run on Mac Excel

I've recently changed from a PC to a Mac. I run a lot of a macros and 99% of them are running fine, but I have one that doesn't work on a Mac.
It runs a set of other macros across all workbooks in a file. To do this it uses strings like this:
Function BrowseFolder(Title As String, _
Optional InitialFolder As String = vbNullString, _
Optional InitialView As Office.MsoFileDialogView = _
msoFileDialogViewList) As String
When I try to run this on the Mac it comes back with an error:
"compile error: variable not defined"
I wonder if anyone could help me with porting this macro over to run on Mac. It was built on Excel 2007 Windows and I'm trying to run it on Excel 2011 Mac.
Option Explicit
Function GetFolder(Optional strPath As String) As String
Dim fldr As FileDialog
Dim sItem As String
Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
With fldr
.Title = "Select a Folder"
.AllowMultiSelect = False
If Not IsEmpty(strPath) Then
.InitialFileName = strPath
End If
If .Show <> -1 Then GoTo NextCode
sItem = .SelectedItems(1)
End With
NextCode:
GetFolder = sItem
Set fldr = Nothing
End Function
Private Sub test()
Dim v As Variant
'V = GetFolder()
v = BrowseFolder("Select folder")
End Sub
Function BrowseFolder(Title As String, _
Optional InitialFolder As String = vbNullString, _
Optional InitialView As Office.MsoFileDialogView = _
msoFileDialogViewList) As String
Dim v As Variant
Dim InitFolder As String
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = Title
.InitialView = InitialView
If Len(InitialFolder) > 0 Then
If Dir(InitialFolder, vbDirectory) <> vbNullString Then
InitFolder = InitialFolder
If Right(InitFolder, 1) <> "\" Then
InitFolder = InitFolder & "\"
End If
.InitialFileName = InitFolder
End If
End If
.Show
On Error Resume Next
Err.Clear
v = .SelectedItems(1)
If Err.Number <> 0 Then
v = vbNullString
End If
End With
BrowseFolder = CStr(v)
End Function
msoFileDialogViewList refers to a specific view of the Windows standard file dialog. The Mac standard file dialog doesn't have equivalent modes; my guess is that the InitialView parameter either doesn't exist or is ignored on the Mac platform.
I'd advise either removing the parameter entirely or using the equivalent integer value (1) instead of the symbolic name.

VB.NET - Checking Windows License State or for Genuine Windows

Hello question answering person of awesomeness!
I am trying to find a way to accurately verify if a Windows 7 machine is currently using an active license and activated. I believe I can initiate a 'cmd.exe' command to run a cscript (slmgr) and parse that information but that seems like an inefficient method.
I have came across an unmanaged windows API called SLGetGenuineInformation ( http://msdn.microsoft.com/en-us/library/windows/desktop/bb648650%28v=vs.85%29.aspx ) however I am not familiar with how to call this in VB.NET or what the variable types should be. I believe VB6 came with some sort of APIViewer that Visual STudio 2010 does not seem to contain.
All relevant Google searches turn up as unrelevant results.
Any suggestions, advice, or guidance on how to proceed or accomplish this goal?
Check this sample vb.net console app, that uses the SLIsGenuineLocal function.
Imports System.Collections.Generic
Imports System.Text
Imports System.Runtime.InteropServices
Imports SLID = System.Guid
Module Module1
Public Enum SL_GENUINE_STATE
SL_GEN_STATE_IS_GENUINE = 0
SL_GEN_STATE_INVALID_LICENSE = 1
SL_GEN_STATE_TAMPERED = 2
SL_GEN_STATE_LAST = 3
End Enum
<DllImportAttribute("Slwga.dll", EntryPoint:="SLIsGenuineLocal", CharSet:=CharSet.None, ExactSpelling:=False, SetLastError:=False, PreserveSig:=True, CallingConvention:=CallingConvention.Winapi, _
BestFitMapping:=False, ThrowOnUnmappableChar:=False)> _
<PreserveSigAttribute()> _
Friend Function SLIsGenuineLocal(ByRef slid As SLID, <[In](), Out()> ByRef genuineState As SL_GENUINE_STATE, ByVal val3 As IntPtr) As UInteger
End Function
Public Function IsGenuineWindows() As Boolean
Dim _IsGenuineWindows As Boolean = False
Dim ApplicationID As New Guid("55c92734-d682-4d71-983e-d6ec3f16059f")
'Application ID GUID http://technet.microsoft.com/en-us/library/dd772270.aspx
Dim windowsSlid As SLID = CType(ApplicationID, Guid)
Try
Dim genuineState As SL_GENUINE_STATE = SL_GENUINE_STATE.SL_GEN_STATE_LAST
Dim ResultInt As UInteger = SLIsGenuineLocal(windowsSlid, genuineState, IntPtr.Zero)
If ResultInt = 0 Then
_IsGenuineWindows = (genuineState = SL_GENUINE_STATE.SL_GEN_STATE_IS_GENUINE)
Else
Console.WriteLine("Error getting information {0}", ResultInt.ToString())
End If
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
Return _IsGenuineWindows
End Function
Sub Main()
If Environment.OSVersion.Version.Major >= 6 Then
'Version 6 can be Windows Vista, Windows Server 2008, or Windows 7
If IsGenuineWindows() Then
Console.WriteLine("Original Windows")
Else
Console.WriteLine("Not Original Windows")
End If
Else
Console.WriteLine("OS Not supoprted")
End If
Console.ReadLine()
End Sub
End Module
If it helps this is VC++ example
#include <slpublic.h>
#pragma comment(lib,"Slwga.lib")
bool IsWindowsGenuine()
{
GUID uid;
RPC_WSTR rpc=(RPC_WSTR)_T("55c92734-d682-4d71-983e-d6ec3f16059f");
UuidFromString(rpc,&uid);
SL_GENUINE_STATE state;
SLIsGenuineLocal(&uid,&state,NULL);
if(state==SL_GENUINE_STATE::SL_GEN_STATE_IS_GENUINE)
return true;
return false;
}
Here is VB Sript that does it:
trComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colWPA = objWMIService.ExecQuery _
("Select * from Win32_WindowsProductActivation")
For Each objWPA in colWPA
Wscript.Echo "Activation Required: " & objWPA.ActivationRequired
Wscript.Echo "Description: " & objWPA.Description
Wscript.Echo "Product ID: " & objWPA.ProductID
Wscript.Echo "Remaining Evaluation Period: " & _
objWPA.RemainingEvaluationPeriod
Wscript.Echo "Remaining Grace Period: " & objWPA.RemainingGracePeriod
Wscript.Echo "Server Name: " & objWPA.ServerName
Next
Source: How to check if a Windows version is Genuine or not?
If you want to read it directly from OS register you can read upon using VB to work whit register here: http://www.codeproject.com/KB/vb/registry_with_vb.aspx

Resources