Can not create a form in vba for another active presentation - forms

I am trying to create a form with vba and for that I am using the following code:
Private Sub createButton_Click()
Dim cSlide As Slide
Dim survey As Shape
Dim text As String
Dim top As Integer
'Dim TempForm As Object ' VBComponent
Dim FormName As String
Dim NewButton As MSForms.CommandButton
Dim TextLocation As Integer
' ** Additional variable
Dim X As Integer
If singleOption.value Then
typ = "radio"
Else
If multipleOption.value Then
typ = "checkBox"
Else
If dropdown.value Then
typ = "dropdown"
Else
MsgBox "Please, select survey type before continue"
Exit Sub
End If
End If
End If
If tagBox = "" Then
MsgBox "Please, write a title before continue"
Exit Sub
End If
If choiceNum = "" Then
MsgBox "Please, set the options number"
Exit Sub
End If
'Locks Excel spreadsheet and speeds up form processing
Application.VBE.MainWindow.Visible = False
'Application.ScreenUpdating = False
choNum = choiceNum
' Create the UserForm
Set TempForm = ActivePresentation.VBProject.VBComponents.Add(vbext_ct_MSForm)
'TempForm.Activate
'Set Properties for TempForm
With TempForm
.Properties("Caption") = "Possible answers"
.Properties("Width") = 300
.Properties("Height") = 10 + 34 * choiceNum + 50
End With
FormName = TempForm.Name
For i = 1 To choiceNum
Set newTab = TempForm.Designer.Controls.Add("Forms.Label.1", "label" & i, True)
With newTab
.Caption = "Answer" & i
.width = 40
.height = 15
.top = 10 + 30 * (i - 1)
.left = 10
End With
Set cCntrl = TempForm.Designer.Controls.Add("Forms.TextBox.1", "textBox" & i, True)
With cCntrl
.width = 150
.height = 15
.top = 10 + 30 * (i - 1)
.left = 60
.ZOrder (0)
End With
Next i
Set NewButton = TempForm.Designer.Controls.Add("forms.CommandButton.1", "answerButton", True)
With NewButton
.Caption = "Create survey"
.left = 60
.top = 30 * choiceNum + 10
End With
ActiveWindow.Selection.Unselect
Set cSlide = Application.ActiveWindow.View.Slide
Set survey = cSlide.Shapes.AddTextbox(msoTextOrientationHorizontal, 20, 20, 400, 20)
survey.TextFrame.TextRange.Font.Size = 25
survey.TextFrame.TextRange.text = tagBox
height = survey.height
survey.Select
'X = ActivePresentation.VBProject.VBComponents(FormName).CodeModule.CountOfLines
With TempForm.CodeModule
X = .CountOfLines + 1
.InsertLines X + 1, "Sub answerButton_Click()"
.InsertLines X + 2, " Dim cSlide As Slide"
.InsertLines X + 3, " Dim survey As Shape"
.InsertLines X + 4, " Dim top As Integer"
.InsertLines X + 5, " Set cSlide = Application.ActiveWindow.View.Slide"
.InsertLines X + 6, " top = 30 + surveyCreation.height - 20"
.InsertLines X + 7, " "
.InsertLines X + 8, " For i = 1 To surveyCreation.choNum"
.InsertLines X + 9, " "
.InsertLines X + 10, " top = top + 15"
.InsertLines X + 11, " Set survey = cSlide.Shapes.AddTextbox(msoTextOrientationHorizontal, 30, top, 400, 10)"
.InsertLines X + 12, " survey.TextFrame.TextRange.text = Me.Controls(i * 2 - 1).Text"
.InsertLines X + 13, " "
.InsertLines X + 14, " survey.TextFrame.TextRange.ParagraphFormat.Bullet = True"
.InsertLines X + 15, " survey.TextFrame.TextRange.ParagraphFormat.Bullet.Type = ppBulletUnnumbered"
.InsertLines X + 16, " survey.Select Replace:=False"
.InsertLines X + 17, " Next i"
.InsertLines X + 18, " With ActiveWindow.Selection.ShapeRange"
.InsertLines X + 19, " .Group.title = ""Dink survey creation"" & surveyCreation.typ"
.InsertLines X + 20, "End With"
.InsertLines X + 21, "Application.VBE.ActiveVBProject.VBComponents.Remove Application.VBE.ActiveVBProject.VBComponents(Application.VBE.ActiveVBProject.VBComponents.Count)"
.InsertLines X + 22, "End Sub"
End With
'TempForm.Activate
tagBox.text = ""
choiceNum = ""
'ActivePresentation.VBProject.VBComponents.Add vbext_ct_MSForm
surveyCreation.Hide
'TempForm.Show
VBA.UserForms.Add(FormName).Show
ActivePresentation.VBProject.UserForms
End Sub
It is working well if I run the code in the presentation were I create the macro but if I want to exec it in another other it gives me the "object required" error. I try with ActivePresentation.VBA witch is not even compiling.
EDIT:
I create a ppam file and add it to powerpoint but it is giving me the same problem even in the presentation were I create it. So if I exec the code in the presentation were I create it, it works. But if I exec the ppam code (I add a button to exec it) it is giving me object required error.

OK, I have had some time to test this out.
I add some code which will create a standard code module at runtime in the ActivePresentation, with one subroutine called ShowMe. This subroutine can then be called from:
Application.Run ActivePresentation.Name & "!ShowMe"
Here is the sample code. I have tested it in a PPAM file and it successfully creates & shows the UserForm in the ActivePresentation.
Option Explicit
Sub Test()
Dim TempForm As Object 'VBComponent / Late Binding
Dim showModule As Object 'VBComponent
Dim FormName As String
Dim choiceNum As Long: choiceNum = 3
Dim vbComps As Long
Dim X As Long
Set TempForm = ActivePresentation.VBProject.VBComponents.Add(3) 'vbext_ct_MSForm
With TempForm
.Properties("Caption") = "Possible answers"
.Properties("Width") = 300
.Properties("Height") = 10 + 34 * choiceNum + 50
FormName = .Properties("Name")
End With
'## Insert a standard code module which will contain a subroutine to show the TempForm
Set showModule = ActivePresentation.VBProject.VBComponents.Add(1) 'vbext_ct_StdModule
With showModule.CodeModule
X = .CountOfLines + 1
.InsertLines X + 1, "Sub ShowMe()"
.InsertLines X + 2, " " & FormName & ".Show"
.InsertLines X + 3, "End Sub"
End With
Application.Run ActivePresentation.Name & "!ShowMe"
'## Remove the module & user form created, above
ActivePresentation.VBProject.VBComponents.Remove TempForm
ActivePresentation.VBProject.VBComponents.Remove showModule
'## Clean up
Set TempForm = Nothing
Set showModule = Nothing
End Sub
While I think there is maybe another way of achieving this (similar to what you were trying with a .Show method), I was not able to make that work. The above method seems to be reliable.
NOTE I am using Option Explicit. Your code has undeclared variables so this will raise some warnings and your code will not execute until you clean it up.

I haven't studied the code in detail, but choose the File menu (Backstage View in 2010) PowerPoint Options, Trust Center, click Trust Center Settings and check "Trust access to the vba project object model".

Related

Remove Marks on Charts

I have a problem with my code, I want to evaluate a Report with Charts.
What my Macro currently does is, Create for every single column a Row for a nominal, upper, lower tolerance. Then It creates with this values a chart.
After this it starts with the Sorting and then it removes the Marker Points, but here my Problems already start.
I would like to create the charts later for example on pos A100 or A50 or something.
Then the Marker Points, I would like to keep the Points on the result line but not on the 3 created, but I found no way 
Remove the Markers, but it removes all, i would really like to remove them only for
FullSeriesCollection(2).format.Line
FullSeriesCollection(3).format.Line
FullSeriesCollection(4).format.Line
Would be nice if someone would have an idea.. :)
Thanks in advance,
' Unload UFormTools
UFormTools.Hide
Application.ScreenUpdating = False
Sheets("Original Values").Select
Dim lngC As Long, lngR As Long
Dim i As Long
Dim c As Byte
Application.ScreenUpdating = False
With ActiveSheet
lngC = (.Cells(17, 4).End(xlToRight).Column - 4) * 4
For i = 4 To lngC Step 4
lngR = .Cells(.Rows.Count, i).End(xlUp).Row
For c = 1 To 3
.Columns(i + c).EntireColumn.Insert
Next c
.Cells(17, i).AutoFill Destination:=.Range(.Cells(17, i), .Cells(17, i + 3)), Type:=xlFillCopy
.Range(.Cells(28, i + 1), .Cells(lngR, i + 1)).Value = .Cells(18, i).Value
.Range(.Cells(28, i + 2), .Cells(lngR, i + 2)).Value = .Cells(18, i).Value + .Cells(19, i).Value
.Range(.Cells(28, i + 3), .Cells(lngR, i + 3)).Value = .Cells(18, i).Value + .Cells(20, i).Value
.Shapes.AddChart2(332, xlLineMarkers).Select
With ActiveChart
.SetSourceData Source:=Union(ActiveSheet.Range(ActiveSheet.Cells(17, i), ActiveSheet.Cells(17, i + 3)), _
ActiveSheet.Range(ActiveSheet.Cells(28, i), ActiveSheet.Cells(lngR, i + 3)))
' .Legend.Delete
.ChartTitle.Text = ActiveSheet.Cells(17, i).Value
.ChartTitle.format.TextFrame2.TextRange.Characters.Text = ActiveSheet.Cells(17, i).Value
With .ChartTitle.format.TextFrame2.TextRange.Characters(1, Len(ActiveSheet.Cells(17, i).Value)).ParagraphFormat
.TextDirection = msoTextDirectionLeftToRight
.Alignment = msoAlignCenter
End With
With .FullSeriesCollection(3).format.Line
.Visible = msoTrue
.ForeColor.RGB = RGB(255, 0, 0)
.Transparency = 0
End With
With .FullSeriesCollection(4).format.Line
.Visible = msoTrue
.ForeColor.RGB = RGB(255, 0, 0)
.Transparency = 0
End With
With .FullSeriesCollection(2).format.Line
.Visible = msoTrue
.ForeColor.ObjectThemeColor = msoThemeColorText1
.ForeColor.TintAndShade = 0
.ForeColor.Brightness = 0
.Transparency = 0
.Visible = msoTrue
.DashStyle = msoLineDash
.Weight = 1.5
End With
With .FullSeriesCollection(1).format.Line
.Visible = msoTrue
.Weight = 3
End With
.FullSeriesCollection(1).Smooth = True
.Axes(xlValue).MinimumScaleIsAuto = True
.Axes(xlValue).MinimumScaleIsAuto = True
End With
Next i
End With
' Sort and Arrange Charts, but another Position to Start would be nice.. (for example A100)
Dim MyWidth As Single, MyHeight As Single
Dim NumWide As Long
Dim iChtIx As Long, iChtCt As Long
MyWidth = 300
MyHeight = 200
NumWide = 4
iChtCt = ActiveSheet.ChartObjects.Count
For iChtIx = 1 To iChtCt
With ActiveSheet.ChartObjects(iChtIx)
.Width = MyWidth
.Height = MyHeight
.Left = ((iChtIx - 1) Mod NumWide) * MyWidth
.Top = Int((iChtIx - 1) / NumWide) * MyHeight
End With
Next
' Remove the Markers, but it removes all, i would really like to remove them only for
' FullSeriesCollection(2).format.Line
' FullSeriesCollection(3).format.Line
' FullSeriesCollection(4).format.Line
Dim cht As ChartObject
Dim srs As Series
Dim MarkerCount As Long
For Each cht In ActiveSheet.ChartObjects
cht.Activate
For Each srs In ActiveChart.SeriesCollection
If srs.MarkerStyle <> xlMarkerStyleNone Then
srs.MarkerStyle = xlMarkerStyleNone
MarkerCount = MarkerCount + 1
End If
Next srs
Next cht
Range("A1").Select
Application.ScreenUpdating = True

Libreoffice get bookmark insert in text

In LibreOffice is it possible to get bookmark that is inserted in the text?
With the code below I can get the list of all the bookmarks I have available, but I just wanted the ones that are actually inserted in the text.
XBookmarksSupplier xBookmarksSupplier =
UnoRuntime.queryInterface(XBookmarksSupplier.class,
xCurrentComponent); XNameAccess xNamedBookmarks =
xBookmarksSupplier.getBookmarks();
Hope this helps:
Sub MyBookmarks
Dim oBookmarks As Variant
Dim oElementNames As Variant
Dim oBookmark As Variant
Dim oTextFields As Variant
Dim oEnum As Variant
Dim oTextField As Variant
Dim sSourceName As String
Dim i As Long, j As Long
Dim sResult As String
Rem First step - collect Bookmarks
oBookmarks = ThisComponent.getBookmarks()
oElementNames = oBookmarks.getElementNames()
Rem Create list of Bookmarks to count Text Fields with it
ReDim oBookmark(LBound(oElementNames) To UBound(oElementNames))
For i = LBound(oElementNames) To UBound(oElementNames)
oBookmark(i) = Array(oElementNames(i),0)
Next i
Rem Enumerate Text Fields
oTextFields = ThisComponent.getTextFields()
oEnum = oTextFields.createEnumeration()
Do While oEnum.hasMoreElements()
oTextField = oEnum.nextElement()
sSourceName = oTextField.SourceName
For i = LBound(oBookmark) To UBound(oBookmark)
If oBookmark(i)(0) = sSourceName Then
oBookmark(i)(1) = oBookmark(i)(1) + 1
Exit For
EndIf
Next i
Loop
Rem Show results
sResult = ""
For i = LBound(oBookmark) To UBound(oBookmark)
If oBookmark(i)(1) > 0 Then
sResult = sResult + oBookmark(i)(0) + " (" + oBookmark(i)(1) + ")" + Chr(10)
EndIf
Next i
If Len(sResult) > 0 Then
sResult = Left(sResult, Len(sResult)-1)
MsgBox("The text of the document uses Bookmarks:" + Chr(10) + sResult, MB_ICONINFORMATION, "Used Bookmarks")
Else
MsgBox("No Bookmarks are used in the text of the document", MB_ICONEXCLAMATION, "No Bookmarks")
EndIf
sResult = ""
For i = LBound(oBookmark) To UBound(oBookmark)
If oBookmark(i)(1) = 0 Then
sResult = sResult + oBookmark(i)(0) + ", "
EndIf
Next i
If Len(sResult) > 0 Then
MsgBox("Bookmarks that are not used in the text of the document:" + Chr(10) + Left(sResult, Len(sResult)-2), MB_ICONINFORMATION, "Not Used Bookmarks")
EndIf
End Sub

Converting VBS to web form

I need to create a web form that -- 1. checks if a serial number is correct. I have the script that does this in VBScript and I am trying to incorporate that into a form. It is a simple algorithm as shown below (the licence format is 9999-999999):
Dim strID
Dim ColCSum3
Dim ChkVal
Dim InitVal
strID = InputBox("Please enter the the serial number to verify", "Verify serial")
If strID = "" Then wscript.Quit
If mid(strID, 5, 1) <> "-" Or Len(strID) <> 11 Then MsgBox "Invalid number format...", 16, "Input error": wscript.Quit
InitVal = CLng(Left(strID, 1))
ChkVal = CLng(Mid(strID, 2, 3))
ColCSum3 = (2 * CLng(Mid(strID, 6, 1)) + _
7 * CLng(Mid(strID, 7, 1)) + _
6 * CLng(Mid(strID, 8, 1)) + _
3 * CLng(Mid(strID, 9, 1)) + _
5 * CLng(Mid(strID, 10, 1)) + _
4 * CLng(Mid(strID, 11, 1))) * 3
If 11 * InitVal + ColCSum3 + 3 = ChkVal Then
MsgBox strID & " is a valid serial number..", 64, "Validated"
Else
MsgBox strID & " is not a valid serial number", 48, "Invalid"
End If
and 2. Once this works, would the key inputed by the user be able to get stored into a database somewhere so that it does not get used again? So I guess the form would also have to check against this field of the database.
The main site is in WordPress but I could set this up as a standalone page if need be. Maybe there is a good WP form plugin that is capable of doing this?
Many thanks.

How can I camelCase a phrase with Dragon NaturallySpeaking's advanced scripting?

From time to time, typically when coding, I would like to dictate a phrase so that it is camelCased a phrase. For example, when I dictate sentence generator I would like Dragon NaturallySpeaking to write sentenceGenerator.
How can I camelCase a phrase with Dragon NaturallySpeaking's advanced scripting?
Same question for Dragon Dictate: How can I convert a series of words into camel case in AppleScript?
You can use this function:
' CamelCases the previous <1to10> words:
' Voice command name: CamelCase <1to10>
' Author: Edgar
' URL: https://www.knowbrainer.com/forums/forum/messageview.cfm?FTVAR_FORUMVIEWTMP=Linear&catid=12&threadid=14634&discTab=true
' URL mirror: https://web.archive.org/web/20170606015010/https://www.knowbrainer.com/forums/forum/messageview.cfm?FTVAR_FORUMVIEWTMP=Linear&catid=12&threadid=14634&discTab=true
' Tested with Dragon NaturallySpeaking 12.5 with Windows 7 SP1 x64 Ultimate
Sub Main
Dim camelVariable, dictate, firstCharacter As String
Dim wasSpace, isLower, trailingSpace As Boolean
Dim dictationLength As Integer
For increment = 1 To Val (ListVar1)
SendKeys "+^{Left}", 1
Next increment
Wait 0.2
SendKeys "^c", 1
Wait 0.3
dictate = Clipboard
Wait 0.3
dictationLength = Len (dictate)
If Mid (dictate, dictationLength, 1) = " " Then trailingSpace = True
'Dim testing As String
'testing = "#" + Mid (dictate, 1, dictationLength) + "#"
'MsgBox testing
dictate = Trim (dictate)
firstCharacter = Mid (dictate, 1, 1)
firstCharacter = LCase (firstCharacter)
camelVariable = firstCharacter
dictationLength = Len (dictate)
If dictationLength > 1 Then
For increment = 2 To dictationLength
firstCharacter = Mid (dictate, increment, 1)
If firstCharacter = " " Then
wasSpace = True
Else
If wasSpace = True Then firstCharacter = UCase (firstCharacter)
camelVariable = camelVariable + firstCharacter
wasSpace = False
End If
Next increment
End If
If leadingSpace = True Then camelVariable = " " + camelVariable
If trailingSpace = True Then camelVariable = camelVariable + " "
SendKeys camelVariable
End Sub
or
' CamelCases the previous dictated words:
' Voice command name: CamelCase that
' Author: Heather
' URL: https://www.knowbrainer.com/forums/forum/messageview.cfm?FTVAR_FORUMVIEWTMP=Linear&catid=12&threadid=14634&discTab=true
' URL mirror: https://web.archive.org/web/20170606015010/https://www.knowbrainer.com/forums/forum/messageview.cfm?FTVAR_FORUMVIEWTMP=Linear&catid=12&threadid=14634&discTab=true
' Tested with Dragon NaturallySpeaking 12.5 with Windows 7 SP1 x64 Ultimate
Option Explicit
Sub Main
Dim engCtrl As New DgnEngineControl
Dim Text As String
Dim VarText As String
HeardWord "cut","that"
Text = Clipboard
SendDragonKeys "" & CamelCase(Text)
End Sub
Public Function CamelCase(strInput As String) As String
Dim i As Integer
Dim sMid As String
Dim foundSpace As Boolean
For i = 1 To Len(strInput)
sMid = Mid(strInput, i, 1)
Select Case Asc(sMid)
Case 32:
foundSpace = True
Case 65 To 90:
If i = 1 Then
CamelCase = CamelCase + LCase(sMid)
Else
CamelCase = CamelCase + sMid
End If
foundSpace = False
Case 97 To 122:
If foundSpace Then
CamelCase = CamelCase + UCase(sMid)
Else
CamelCase = CamelCase + sMid
End If
foundSpace = False
Case Else:
CamelCase = CamelCase + sMid
foundSpace = False
End Select
Next i
End Function
or
' CamelCases the next dictated words:
' Voice command name: CamelCase <dictation>
' Author: Edgar
' URL: https://www.knowbrainer.com/forums/forum/messageview.cfm?FTVAR_FORUMVIEWTMP=Linear&catid=12&threadid=14634&discTab=true
' URL mirror: https://web.archive.org/web/20170606015010/https://www.knowbrainer.com/forums/forum/messageview.cfm?FTVAR_FORUMVIEWTMP=Linear&catid=12&threadid=14634&discTab=true
' Requires Dragon NaturallySpeaking 13 Professional or higher, because the variable <dictation> was introduced in Dragon NaturallySpeaking 13 Professional.
Sub Main
Dim camelVariable, dictate, firstCharacter As String
Dim wasSpace, isLower As Boolean
Dim dictationLength As Integer
dictate = ListVar1
dictate = Trim (dictate)' probably unnecessary
firstCharacter = Mid (dictate, 1, 1)
firstCharacter = LCase (firstCharacter)
camelVariable = firstCharacter
dictationLength = Len (dictate)
If dictationLength > 1 Then
For increment = 2 To dictationLength
firstCharacter = Mid (dictate, increment, 1)
If firstCharacter = " " Then
wasSpace = True
Else
If wasSpace = True Then firstCharacter = UCase (firstCharacter)
camelVariable = camelVariable + firstCharacter
wasSpace = False
End If
Next increment
End If
SendKeys " " + camelVariable + " "
End Sub
(source) (mirror)
The answer from 2017 has syntax issues. I just coded and tested this for Dragon 15:
'#Language "WWB-COM"
' Command name: case camel <dictation>
'
' Description:
' Applies camel case to provided phrase.
'
' Usage:
' "case camel looks good to me" -> "looksGoodToMe"
Option Explicit
Sub Main
Dim phrase As String
Dim result As String
Dim wasSpace As Boolean
Dim i As Integer
phrase = ListVar1
phrase = Trim(phrase)
wasSpace = False
For i = 0 To Len(phrase) - 1
If i = 0 Then
result = LCase(Mid(phrase,i + 1,1))
ElseIf Mid(phrase,i + 1,1) = " " Then
wasSpace = True
ElseIf wasSpace Then
result += UCase(Mid(phrase,i + 1,1))
wasSpace = False
Else
result += LCase(Mid(phrase,i + 1,1))
End If
Next
SendKeys result
End Sub

VB 6 failed send to email server

I am trying to write a program that will send email with an attachment in VB6. I'm using winsock and smtp.gmail.com as my mail server but it doesn't work. Failed to connect to mail server.The code works fine. My only problem is when I try to send message it doesn't connect please help me thanks in advance.
Here's the code
Dim objBase64 As New Base64
Dim bTrans As Boolean
Dim m_iStage As Integer
Dim Sock As Integer
Dim RC As Integer
Dim Bytes As Integer
Dim ResponseCode As Integer
Dim path As String
Private Type OPENFILENAME
lStructSize As Long
hwndOwner As Long
hInstance As Long
lpstrFilter As String
lpstrCustomFilter As String
nMaxCustFilter As Long
nFilterIndex As Long
lpstrFile As String
nMaxFile As Long
lpstrFileTitle As String
nMaxFileTitle As Long
lpstrInitialDir As String
lpstrTitle As String
flags As Long
nFileOffset As Integer
nFileExtension As Integer
lpstrDefExt As String
lCustData As Long
lpfnHook As Long
lpTemplateName As String
End Type
Const OFN_READONLY = &H1
Const OFN_OVERWRITEPROMPT = &H2
Const OFN_HIDEREADONLY = &H4
Const OFN_NOCHANGEDIR = &H8
Const OFN_SHOWHELP = &H10
Const OFN_ENABLEHOOK = &H20
Const OFN_ENABLETEMPLATE = &H40
Const OFN_ENABLETEMPLATEHANDLE = &H80
Const OFN_NOVALIDATE = &H100
Const OFN_ALLOWMULTISELECT = &H200
Const OFN_EXTENSIONDIFFERENT = &H400
Const OFN_PATHMUSTEXIST = &H800
Const OFN_FILEMUSTEXIST = &H1000
Const OFN_CREATEPROMPT = &H2000
Const OFN_SHAREAWARE = &H4000
Const OFN_NOREADONLYRETURN = &H8000
Const OFN_NOTESTFILECREATE = &H10000
Const OFN_NONETWORKBUTTON = &H20000
Const OFN_NOLONGNAMES = &H40000
Const OFN_EXPLORER = &H80000
Const OFN_NODEREFERENCELINKS = &H100000
Const OFN_LONGNAMES = &H200000
Const OFN_SHAREFALLTHROUGH = 2
Const OFN_SHARENOWARN = 1
Const OFN_SHAREWARN = 0
Private Declare Function GetSaveFileName Lib "comdlg32" Alias "GetSaveFileNameA" (pOpenfilename As OPENFILENAME) As Long
Private Declare Function timeGetTime Lib "winmm.dll" () As Long
Private Declare Function GetSystemMenu Lib "user32" (ByVal hWnd As Long, ByVal bRevert As Long) As Long
Private Declare Function GetMenuItemCount Lib "user32" (ByVal hMenu As Long) As Long
Private Declare Function RemoveMenu Lib "user32" (ByVal hMenu As Long, ByVal nPosition As Long, ByVal wFlags As Long) As Long
Private Declare Function DrawMenuBar Lib "user32" (ByVal hWnd As Long) As Long
Const MF_BYPOSITION = &H400&
Const MF_REMOVE = &H1000&
Dim Mime As Boolean
Dim arrRecipients As Variant
Dim CurrentE As Integer
Private Sub Attachment_Click()
path = SaveDialog(Me, "*.*", "Attach File", App.path)
If path = "" Then Exit Sub
AttachmentList.AddItem path
Mime = True
AttachmentList.ListIndex = AttachmentList.ListCount - 1
End Sub
Private Sub AttachmentList_Click()
fSize = Int((FileLen(AttachmentList) / 1024) * 100 + 0.5) / 100
AttachmentList.ToolTipText = AttachmentList & " (" & fSize & " KB)"
End Sub
Private Sub AttachmentList_OLEDragDrop(Data As DataObject, Effect As Long, Button As Integer, Shift As Integer, X As Single, Y As Single)
For I = 1 To Data.Files.Count
If (GetAttr(Data.Files.Item(I)) And vbDirectory) = 0 Then AttachmentList.AddItem Data.Files.Item(I): Mime = True: AttachmentList.ListIndex = AttachmentList.ListCount - 1
Next I
End Sub
Private Sub DataArrival_MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single)
Dim MsgBuffer As String * 2048
On Error Resume Next
If Sock > 0 Then
Bytes = recv(Sock, ByVal MsgBuffer, 2048, 0)
If Bytes > 0 Then
ServerResponse = Mid$(MsgBuffer, 1, Bytes)
DataArrival = DataArrival & ServerResponse & vbCrLf
DataArrival.SelStart = Len(DataArrival)
If bTrans Then
If ResponseCode = Left$(MsgBuffer, 3) Then
m_iStage = m_iStage + 1
Transmit m_iStage
Else
closesocket (Sock)
Call EndWinsock
Sock = 0
Process = "The Server responds with an unexpected Response Code!"
Exit Sub
End If
End If
ElseIf WSAGetLastError() <> WSAEWOULDBLOCK Then
closesocket (Sock)
Call EndWinsock
Sock = 0
End If
End If
Refresh
End Sub
Private Sub delattach_Click()
If AttachmentList.ListCount = 0 Or AttachmentList.ListIndex = -1 Then Exit Sub
tmpIndex = AttachmentList.ListIndex
AttachmentList.RemoveItem (AttachmentList.ListIndex)
If AttachmentList.ListCount = 0 Then Mime = False: Attachment.ToolTipText = "Drag & Drop your attachments here" Else If AttachmentList.ListIndex = 0 Then AttachmentList.ListIndex = tmpIndex Else AttachmentList.ListIndex = tmpIndex - 1
End Sub
Sub DisableX(frm As Form)
Dim hMenu As Long
Dim nCount As Long
hMenu = GetSystemMenu(frm.hWnd, 0)
nCount = GetMenuItemCount(hMenu)
Call RemoveMenu(hMenu, nCount - 1, MF_REMOVE Or MF_BYPOSITION)
Call RemoveMenu(hMenu, nCount - 2, MF_REMOVE Or MF_BYPOSITION)
DrawMenuBar frm.hWnd
End Sub
Private Sub Exit_Click()
On Error Resume Next
Call Startrek
closesocket Sock
Call EndWinsock
End
End Sub
Private Sub Form_Load()
Call DisableX(Me)
End Sub
Function IsConnected2Internet() As Boolean
On Error Resume Next
If MyIP = "127.0.0.1" Or MyIP = "" Then IsConnected2Internet = False Else IsConnected2Internet = True
End Function
Function SaveDialog(Form1 As Form, Filter As String, Title As String, InitDir As String) As String
Dim ofn As OPENFILENAME
Dim A As Long
ofn.lStructSize = Len(ofn)
ofn.hwndOwner = Form1.hWnd
ofn.hInstance = App.hInstance
If Right$(Filter, 1) <> "|" Then Filter = Filter & "|"
For A = 1 To Len(Filter)
If Mid$(Filter, A, 1) = "|" Then Mid$(Filter, A, 1) = Chr$(0)
Next A
ofn.lpstrFilter = Filter
ofn.lpstrFile = Space$(254)
ofn.nMaxFile = 255
ofn.lpstrFileTitle = Space$(254)
ofn.nMaxFileTitle = 255
ofn.lpstrInitialDir = InitDir
ofn.lpstrTitle = Title
ofn.flags = OFN_HIDEREADONLY Or OFN_CREATEPROMPT
A = GetSaveFileName(ofn)
If (A) Then
SaveDialog = Left$(Trim$(ofn.lpstrFile), Len(Trim$(ofn.lpstrFile)) - 1)
Else
SaveDialog = ""
End If
End Function
Private Sub SendMimeAttachment()
Dim FileIn As Long
Dim temp As Variant
Dim s As Variant
Dim TempArray() As Byte
Dim Encoded() As Byte
Dim strFile As String
Dim strFile1 As String * 32768
For IAT = 0 To AttachmentList.ListCount - 1
path = AttachmentList.List(IAT)
Mimefilename = Trim$(Right$(path, Len(path) - InStrRev(path, "\")))
FileIn = FreeFile
r
temp = vbCrLf & "--NextMimePart" & vbCrLf
temp = temp & "Content-Type: application/octet-stream; name=Mimefilename" & vbCrLf
temp = temp & "Content-Transfer-Encoding: base64" & vbCrLf
temp = temp & "Content-Disposition: attachment; filename=" & Chr$(34) & Mimefilename & Chr$(34) & vbCrLf
WinsockSendData (temp & vbCrLf)
Open path For Binary Access Read As FileIn
If GetSetting(App.Title, "Settings", "Too big", "") <> "True" Then
If LOF(FileIn) > 2097152 Then
fSize = Int((LOF(FileIn) / 1048576) * 100 + 0.5) / 100
Setu = MsgBox("The current file is " & fSize & " MB of size, extracting from it could take a few minutes, Click Yes to go ahead, No to skip it or Cancel if you don't want to get this message again", vbYesNoCancel)
If Setu = vbYes Then GoTo Cont
If Setu = vbNo Then Close (FileIn): GoTo Anoth Else SaveSetting App.Title, "Settings", "Too big", "True"
End If
End If
Cont:
frm2.Visible = True
Process = "Loading """ & AttachmentList.List(IAT) & """"
Do While Not EOF(FileIn)
If LOF(FileIn) = 0 Then GoTo Anoth
Get FileIn, , strFile1
strFile = strFile & Mid$(strFile1, 1, Len(strFile1) - (Loc(FileIn) - LOF(FileIn)))
strFile1 = ""
DoEvents
frm2.Width = (3300 / 100) * (Len(strFile) * 50 / LOF(FileIn))
lblpcent = Int(Len(strFile) * 50 / LOF(FileIn)) & "%"
If Cancelflag Then Close FileIn: Exit Sub
Loop
Close FileIn
If strFile = "" Then Exit Sub
objBase64.Str2ByteArray strFile, TempArray
objBase64.EncodeB64 TempArray, Encoded
objBase64.Span 76, Encoded, TempArray
strFile = ""
s = StrConv(TempArray, vbUnicode)
For I = 1 To Len(s) Step 8192
ss = Trim$(Mid$(s, I, 8192))
tmpServerSpeed = 150
Start = timeGetTime
Do
DoEvents
Loop Until timeGetTime >= Start + tmpServerSpeed * 20
WinsockSendData (ss)
frm2.Width = 1650 + (3300 / 100) * ((I + Len(ss)) * 50 / Len(s))
lblpcent = 50 + Int((I + Len(ss)) * 50 / Len(s)) & "%"
Process = "Sending " & Mimefilename & "... " & I + Len(ss) & " Bytes from " & Len(s)
DoEvents
Next I
Anoth:
s = ""
Next IAT
WinsockSendData (vbCrLf & "--NextMimePart--" & vbCrLf)
WinsockSendData (vbCrLf & "." & vbCrLf)
End Sub
Private Sub SendMimeConnect_Click()
If Tobox = "" Or InStr(Tobox, "#") = 0 Then
MsgBox "To: Is not correct!"
Exit Sub
End If
If IsConnected = False Then
If MsgBox("No Internet connection has been detected, check for Update anyway?", vbYesNo) = vbNo Then Exit Sub
End If
Sock = ConnectSock(MailServer, 25, DataArrival.hWnd)
If Sock = SOCKET_ERROR Then
Process = "Cannot Connect to " & MailServer & GetWSAErrorString(WSAGetLastError())
closesocket Sock
Call EndWinsock
Exit Sub
End If
Process = "Connected to " & MailServer
bTrans = True
m_iStage = 0
DataArrival = ""
ResponseCode = 220
Call WaitForResponse
End Sub
Sub SendMimetxt(txtFrom, txtTo, txtSubjekt, txtMail)
Dim strToSend As String
Dim strDataToSend As String
If Mime Then
strDataToSend = "From: " & txtFrom & vbCrLf
strDataToSend = strDataToSend & "To: " & txtTo & vbCrLf
strDataToSend = strDataToSend & "Date: " & Format$(Now, "DDDD , dd Mmm YYYY hh:mm:ss AM/PM") & vbCrLf
strDataToSend = strDataToSend & "Subject: " & txtSubjekt & vbCrLf
strDataToSend = strDataToSend & "X-Mailer: " & App.CompanyName & " - " & App.Title & vbCrLf
strDataToSend = strDataToSend & "Mime-Version: 1.0" & vbCrLf
strDataToSend = strDataToSend & "Content-Type: multipart/mixed; boundary=NextMimePart" & vbCrLf
strDataToSend = strDataToSend & "Content-Transfer-Encoding: 7bit" & vbCrLf
strDataToSend = strDataToSend & "This is a multi-part message in MIME format." & vbCrLf & vbCrLf
strDataToSend = strDataToSend & "--NextMimePart" & vbCrLf & vbCrLf
strDataToSend = strDataToSend & Trim$(Mailtxt)
strDataToSend = Replace$(strDataToSend, vbCrLf & "." & vbCrLf, vbCrLf & "." & Chr$(0) & vbCrLf)
For I = 1 To Len(strDataToSend) Step 8192
strToSend = Trim$(Mid$(strDataToSend, I, 8192))
WinsockSendData (strToSend)
frm2.Width = (2400 / 100) * ((I + Len(strToSend)) * 100 / Len(strDataToSend))
lblpcent = Int((I + Len(strToSend)) * 100 / Len(strDataToSend)) & "%"
If Cancelflag Then Exit For
Process = "Sending message body... " & I + Len(strToSend) & " Bytes from " & Len(strDataToSend)
DoEvents
Next I
SendMimeAttachment
Else
strDataToSend = "From: " & txtFrom & vbCrLf
strDataToSend = strDataToSend & "To: " & txtTo & vbCrLf
strDataToSend = strDataToSend & "Date: " & Format$(Now, "DDDD , dd Mmm YYYY hh:mm:ss AM/PM") & vbCrLf
strDataToSend = strDataToSend & "Subject: " & txtSubjekt & vbCrLf
strDataToSend = strDataToSend & "X-Mailer: " & App.CompanyName & " - " & App.Title & vbCrLf & vbCrLf
strDataToSend = strDataToSend & Trim$(txtMail)
strDataToSend = Replace$(strDataToSend, vbCrLf & "." & vbCrLf, vbCrLf & "." & Chr$(0) & vbCrLf)
For I = 1 To Len(strDataToSend) Step 8192
strToSend = Trim$(Mid$(strDataToSend, I, 8192))
WinsockSendData (strToSend)
frm2.Width = (2400 / 100) * ((I + Len(strToSend)) * 100 / Len(strDataToSend))
lblpcent = Int((I + Len(strToSend)) * 100 / Len(strDataToSend)) & "%"
If Cancelflag Then Exit For
Process = "Sending message body... " & I + Len(strToSend) & " Bytes from " & Len(strDataToSend)
DoEvents
Next I
WinsockSendData (vbCrLf & "." & vbCrLf)
End If
End Sub
Sub Startrek()
On Error Resume Next
Dim Rate As Integer
Dim Rate2 As Integer
If WindowState <> 0 Then Exit Sub
Caption = "End Transmission"
GotoVal = (Height / 12)
Rate = 50
For Gointo = 1 To GotoVal
Spd = Timer
Rate2 = Rate / 2
Height = Height - Rate
Top = Top + Rate2
DoEvents
Width = Width - Rate
Left = Left + Rate2
DoEvents
If Width <= 2000 Then Exit For
Rate = (Timer - Spd) * 10000
Next Gointo
WindowState = 1
End Sub
Private Sub Tobox_Change()
arrRecipients = Split(Tobox, ",")
End Sub
Private Sub Transmit(iStage As Integer)
Dim Helo As String
Dim pos As Integer
Select Case m_iStage
Case 1
Helo = Frombox
pos = Len(Helo) - InStr(Helo, "#")
Helo = Right$(Helo, pos)
ResponseCode = 250
WinsockSendData ("HELO " & Helo & vbCrLf)
Call WaitForResponse
Case 2
ResponseCode = 250
WinsockSendData ("MAIL FROM: <" & Trim$(Frombox) & ">" & vbCrLf)
Call WaitForResponse
Case 3
ResponseCode = 250
WinsockSendData ("RCPT TO: <" & Trim$(arrRecipients(CurrentE)) & ">" & vbCrLf)
Call WaitForResponse
Case 4
ResponseCode = 354
WinsockSendData ("DATA" & vbCrLf)
Call WaitForResponse
Case 5
ResponseCode = 250
Call SendMimetxt(Frombox, Trim$(arrRecipients(CurrentE)), Subjekt, Mailtxt)
Call WaitForResponse
Case 6
ResponseCode = 221
WinsockSendData ("QUIT" & vbCrLf)
Call WaitForResponse
Process = "Email has been sent!"
frm2.Width = 3300
lblpcent = "100%"
DataArrival = ""
m_iStage = 0
If arrRecipients(CurrentE + 1) <> "" Then
CurrentE = CurrentE + 1
SendMimeConnect_Click
Else
bTrans = False
CurrentE = 0
End If
End Select
End Sub
Private Sub WaitForResponse()
Dim Start As Long
Dim Tmr As Long
Start = timeGetTime
While Bytes > 0
Tmr = timeGetTime - Start
DoEvents '
If Tmr > 20000 Then
Process = "SMTP service error, timed out while waiting for response"
End If
Wend
End Sub
Private Sub WinsockSendData(DatatoSend As String)
Dim RC As Integer
Dim MsgBuffer As String * 8192
MsgBuffer = DatatoSend
RC = send(Sock, ByVal MsgBuffer, Len(DatatoSend), 0)
If RC = SOCKET_ERROR Then
Process = "Cannot Send Request." & Str$(WSAGetLastError()) & _
GetWSAErrorString(WSAGetLastError())
closesocket Sock
Call EndWinsock
Exit Sub
End If
End Sub
I didn't bother to read your code. Too hard. Here's how to do it easily.
Set emailObj = CreateObject("CDO.Message")
emailObj.From = "dc#gail.com"
emailObj.To = "dc#gail.com"
emailObj.Subject = "Test CDO"
emailObj.TextBody = "Test CDO"
emailObj.AddAttachment "c:\windows\win.ini"
Set emailConfig = emailObj.Configuration
emailConfig.Fields("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.gmail.com"
emailConfig.Fields("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 465
emailConfig.Fields("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
emailConfig.Fields("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1
emailConfig.Fields("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = true
emailConfig.Fields("http://schemas.microsoft.com/cdo/configuration/sendusername") = "YourUserName"
emailConfig.Fields("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "Password1"
emailConfig.Fields.Update
emailObj.Send
If err.number = 0 then Msgbox "Done"
Here's how to get files from internet with a high level object. You must use the exact name with http:// as there no helper for incorrect addresses.
Set File = WScript.CreateObject("Microsoft.XMLHTTP")
File.Open "GET", "http://www.microsoft.com", False
File.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 1.1.4322; .NET CLR 3.5.30729; .NET CLR 3.0.30618; .NET4.0C; .NET4.0E; BCD2000; BCD2000)"
File.Send
txt=File.ResponseText
Also for binary files use ado stream. To create a database in memory use adodb recordset (better than a dictionary, array, or a collection), makes sorting a one line command.