Macro for Saving Solidworks part configurations as dxf files - macros

I have to save a lot of dxf files from Solidworks to use for a CNC machine.
I'm looking for help to create a macro to save each configuration of the part as the top view of a part as a .dxf in the same location as the Solidworks file is saved.
I have found two macros which I kind of need to be combined together.
The first one saves all configurations separately as part files
The second one saves a part as a dxf of the top view.
It would be much appreciated if anyone could help me
first macro:
' Macro created by Jeff Parker CSWP/MCP 12/30/02
'
' Rev.1 = Added completion message box. Also verified SolidWorks 2005 compatabliity.
'
' Rev.2 = Fixed macro for x64 bits machines (changed folder browse codes). Also verified SolidWorks 2014 compatabliity.
' (BY: Deepak Gupta www.gupta9665.com 07/26/14)
' Folder Browse Codes: http://www.cpearson.com/excel/browsefolder.aspx
'
' Rev.3 = Fixed macro for Weldment part configuration names having <As Machined> and <As Welded>. Also verified SolidWorks 2016 compatabliity.
' (BY: Deepak Gupta www.gupta9665.com 01/14/16)
'
' DISCLAIMER:
' * These macros are provided free of charge for personal use and/or reference.
' * These macros may be freely distributed, provided the original copyright
' notices remain unchanged and intact.
' * All macros were written to work with SolidWorks 2005.
' * These macros, and corresponding files, are provided as is.
' * There are no warranties, expressed or implied, that these macros will perform
' as indicated, perform to users expectations, or complete a specific task.
' * These macros will change the current SolidWorks document. Use these macros at
' your own risk. Back up your data before using this macro on any SolidWorks
' document.
'
' ******************************************************************************
Dim swApp As SldWorks.SldWorks
Dim Part As SldWorks.ModelDoc2
Dim boolstatus As Boolean
Dim longstatus As Long
Dim Annotation As Object
Dim Gtol As Object
Dim DatumTag As Object
Dim FeatureData As Object
Dim Feature As Object
Dim Component As Object
Dim ConfigNamesArray As Variant
Dim ConfigNameMain As Variant
Dim ConfigName As Variant
Dim NewName As String
Dim PartName As String
Dim OpenName As String
Dim CurrentConfigName As Variant
Dim fileerror As Long
Dim filewarning As Long
Dim OrigConfigName As Variant
Dim Location As Variant
Dim ModLoc As String
Dim MassProps As Variant
Dim Mass As Variant
Dim MassError As Long
Dim ConfigCount As Long
Dim MassPropArrayTest As Long
Dim CustomPropNamesArray As Variant
Dim CustomPropName As Variant
Dim PartSourceName As String
Dim PartSourcePath As String
Dim status As Boolean
Sub main()
Set swApp = Application.SldWorks 'Connect to SolidWorks session
Set Part = swApp.ActiveDoc 'Set Part variable to active doc
If Part Is Nothing Then Exit Sub
ConfigCount = Part.GetConfigurationCount 'Get number of configurations
PartSourceName = Part.GetTitle 'Get name of original part file that contains configurations
If Part.GetType <> swDocPART Then 'Check to see if current document is a part
MsgBox "Only Allowed on Parts, Please open a part and try again.", vbOKOnly, "Error" ' Display error message"
Exit Sub ' Exit this program
ElseIf ConfigCount = 1 Then
MsgBox "Must have at least two configurations before starting macro.", vbOKOnly, "Error" ' Display error message"
Exit Sub ' Exit this program
Else
GoTo Rip
End If
Rip: 'RIP sub section
frmLocation.Show 'Show form
Location = frmLocation.txtPath.Text 'Get user selected location
'---Check to see if location has last backslash---
ModLoc = Right(Location, 1)
If ModLoc <> "\" Then
Location = Location & "\"
End If
ConfigNamesArray = Part.GetConfigurationNames 'Populate the array with all config names
OrigConfigName = ConfigNamesArray(0) 'Get current configuration
For i = 0 To UBound(ConfigNamesArray)
ConfigName = ConfigNamesArray(i) 'Assign next config name to ConfigName variable
Part.ShowConfiguration2 (ConfigName) 'Set next config as current
ConfigName = Replace((Replace(ConfigName, "<As Machined>", "")), "<As Welded>", "")
NewName = Location & ConfigName & ".sldprt" 'Create path
Part.SaveAsSilent NewName, True 'Save as current config name
Next i
PartSourcePath = Part.GetPathName
swApp.CloseDoc PartSourceName 'Close the source file to conserve memory for program
Set Part = Nothing 'Clear part variable
For j = 0 To UBound(ConfigNamesArray)
ConfigNameMain = ConfigNamesArray(j) 'Populate ConfigNameMain with current name
ConfigNameMain = Replace((Replace(ConfigNameMain, "<As Machined>", "")), "<As Welded>", "")
OpenName = Location & ConfigNameMain & ".sldprt" 'Set location of file to open
fileerror = swFileNotFoundError 'Default system error message
filewarning = swFileSaveWarning_NeedsRebuild 'Default warning message
swApp.OpenDoc6 OpenName, 1, 0, "", fileerror, filewarning 'Open saved configuration file
Set Part = swApp.ActiveDoc 'Set newly opened file as current
Part.DeleteDesignTable 'Delete design table if present
For k = 0 To UBound(ConfigNamesArray) 'Delete all configurations from new file
ConfigName = ConfigNamesArray(k)
Part.DeleteConfiguration2 (ConfigName)
Next k
Part.EditConfiguration3 ConfigNameMain, "Default", "", "", 0 'Rename leftover config to default
Part.ViewZoomtofit2 'Make part zoom to fit so icon looks good
Part.Save2 (True) 'Save newly modified part
Set Part = Nothing 'Clear Part variable
swApp.CloseDoc ConfigNameMain & ".sldprt" 'Close current part
Next j
swApp.OpenDoc6 PartSourcePath, 1, 0, "", fileerror, filewarning 'Open original source file
Set Part = swApp.ActiveDoc 'Set original part as current
Part.ShowConfiguration2 (OrigConfigName) 'Set original part to original status
MsgBox "Here is where you can find your files: " & Chr(13) & Location, vbInformation, "Configuration Rip Success!"
Location = "" 'Clear location variable
End Sub 'Close program
second macro:
Option Explicit
Dim swApp As SldWorks.SldWorks
Dim swModel As SldWorks.ModelDoc2
Dim swPart As SldWorks.PartDoc
Dim sModelName As String
Dim sPathName As String
Dim varAlignment As Variant
Dim dataAlignment(11) As Double
Dim varViews As Variant
Dim dataViews(0) As String
Sub main()
Set swApp = Application.SldWorks
Set swModel = swApp.ActiveDoc
Set swPart = swModel
sModelName = swModel.GetPathName
sPathName = Left(sModelName, Len(sModelName) - 6) & "dxf"
dataAlignment(0) = 0#
dataAlignment(1) = 0#
dataAlignment(2) = 0#
dataAlignment(3) = 1#
dataAlignment(4) = 0#
dataAlignment(5) = 0#
dataAlignment(6) = 0#
dataAlignment(7) = 0#
dataAlignment(8) = -1#
dataAlignment(9) = 0#
dataAlignment(10) = 1#
dataAlignment(11) = 0#
varAlignment = dataAlignment
dataViews(0) = "*Top"
varViews = dataViews
swPart.ExportToDWG2 sPathName, sModelName, swExportToDWG_e.swExportToDWG_ExportAnnotationViews, True, varAlignment, False, False, 0, varViews
End Sub

Try the following codes which exports each configuration of the active part as DXF.
Option Explicit
Dim swApp As SldWorks.SldWorks
Dim swModel As SldWorks.ModelDoc2
Dim sModelName As String
Dim sPathName As String
Dim vConfNameArr As Variant
Dim i As Long
Dim sConfigName As String
Dim bRebuild As Boolean
Dim swPart As SldWorks.PartDoc
Dim nFileName As String
Dim varAlignment As Variant
Dim dataAlignment(11) As Double
Dim varViews As Variant
Dim dataViews(0) As String
Sub Main()
Set swApp = Application.SldWorks
Set swModel = swApp.ActiveDoc
' Is document active?
If swModel Is Nothing Then
swApp.SendMsgToUser2 "A Sheet Metal Part must be open.", swMbWarning, swMbOk
Exit Sub
End If
' Is it a part document?
If swModel.GetType <> SwConst.swDocPART Then
swApp.SendMsgToUser2 "A Sheet Metal Part must be open.", swMbWarning, swMbOk
Exit Sub
End If
sModelName = swModel.GetPathName
sPathName = Left(sModelName, InStrRev(sModelName, "\"))
vConfNameArr = swModel.GetConfigurationNames
For i = 0 To UBound(vConfNameArr)
sConfigName = vConfNameArr(i)
If Not UCase(sConfigName) Like "*FLAT*" Then
swModel.ShowConfiguration2 (sConfigName)
bRebuild = swModel.ForceRebuild3(False)
nFileName = sPathName & sConfigName & ".DXF"
Set swPart = swModel
dataAlignment(0) = 0#
dataAlignment(1) = 0#
dataAlignment(2) = 0#
dataAlignment(3) = 0#
dataAlignment(4) = 0#
dataAlignment(5) = 0#
dataAlignment(6) = 0#
dataAlignment(7) = 0#
dataAlignment(8) = 0#
dataAlignment(9) = 0#
dataAlignment(10) = 0#
dataAlignment(11) = 0#
varAlignment = dataAlignment
dataViews(0) = "*Top"
varViews = dataViews
'Export Top View
swPart.ExportToDWG2 nFileName, sModelName, 3, True, varAlignment, False, False, 0, varViews
End If
Next i
End Sub

Related

Ho to select one spreadsheet after another in LibreOffice?

How to select spreadsheets one after another in Libre Office to perform some action in them?
In excel vba the following code worked, but it does not work in LibreOffice
Dim wb as Workbook
Dim ws as Worksheet
Set wb = ActiveWorkbook
For Each ws in wb.Worksheets
'Do something here
End if
Next
Could anyone help me with that?
First of all get the oSheets object (which is what is called Worksheets in Excel) of ThisComponent (which is what is called ActiveWorkbook in Excel)
Sub sheetProcessing()
Dim oSheets As Variant, oSheet As Variant
Dim i As Long
' By Sheet index
oSheets = ThisComponent.getSheets()
For i = 0 To oSheets.getCount() - 1
oSheet = oSheets.getByIndex(i)
Print oSheet.getName() & " - " & oSheet.getCellByPosition(0, 0).getString()
Next i
' Or by Element Names
Dim oElementNames As Variant
oElementNames = oSheets.getElementNames()
For i = LBound(oElementNames) To UBound(oElementNames)
oSheet = oSheets.getByName(oElementNames(i))
Print oSheet.getName() & " - " & oSheet.getCellByPosition(0, 0).getString()
Next i
' Or easiest
For Each oSheet In oSheets
Print oSheet.getName() & " - " & oSheet.getCellByPosition(0, 0).getString()
Next oSheet
End Sub

How to read / write binary file with Unicode filename in VB6

I have this code:
Function cpyBIN(cpFilename As String)
Dim litefile() As Byte
Dim FN As Integer
Dim xlof As Long
FN = 1
Open cpFilename For Binary As FN
xlof = LOF(FN)
ReDim litefile(xlof)
Get FN, , litefile
Open cpFilename & "Backup" For
Binary As #2
Put #2, , litefile
Close #2
Close FN
End Function
and I use it in a Form like this :
Private Sub cmdBackup_Click()
Dim strComputer, objWMIService, colFiles, objfile
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colFiles = objWMIService.ExecQuery("Select * from CIM_Datafile where Drive='D:' and path='\\contoh\\'")
For Each objfile In colFiles
cpyBIN (objfile.Name)
Next
End Sub
in the contoh folder there are 2 sample files:
namafile.exe
namafile♣♣♠.exe
when I run the code there is an error message like in the picture:
the error is in the line as shown in the picture:
how to make it supports unicode filename?
or
is there any replacement for this function??
There are several ways to make a copy of a file with Unicode file names. The first way is by using the Windows API:
Declare Function CopyFileW Lib "kernel32.dll" (ByVal lpExistingFileName As Long, _
ByVal lpNewFileName As Long, Optional ByVal bFailIfExists As Long) As Long
For Each objfile In colFiles
CopyFileW StrPtr(objfile.Name), StrPtr(objfile.Name & ".Backup")
Next
The second way is by using a FileSystemObject:
Dim fso As FileSystemObject
Set fso = New FileSystemObject
For Each objfile In colFiles
fso.CopyFile objfile.Name, objfile.Name & ".Backup", True
Next
The third way is by using an ADO Stream:
Dim s As ADODB.Stream
Set s = New ADODB.Stream
s.Open
s.Type = adTypeBinary
For Each objFile In colFiles
s.LoadFromFile objFile.Name
s.SaveToFile objFile.Name & ".Backup", adSaveCreateOverWrite
Next
s.Close
If you want to read data, I would use an ADO Stream:
Dim s As ADODB.Stream
Set s = New ADODB.Stream
s.Open
s.Type = adTypeBinary
For Each objFile In colFiles
s.LoadFromFile objFile.Name
data = s.Read()
'use the data somehow
Next
s.Close

Macro for Saving Solidworks parts as dxf files

I have to save a lot of dxf files from solidworks to use for a CNC machine.
I'm looking for help to create a macro to save the top view of a part as a .dxf in the same location as the solidworks file is saved.
I would like it to first save the solidworks part, and to replace any existing dxf if there's one with the same name already saved in that location.
I could find macros for drawing files and for sheet metal parts but have been unable to edit these to work for a normal part.
much appreciated if anyone could point me in the right direction.
Try this.
It will export the top view of the part to dxf
(Adapted from ExportToDWG2)
Option Explicit
Dim swApp As SldWorks.SldWorks
Dim swModel As SldWorks.ModelDoc2
Dim swPart As SldWorks.PartDoc
Dim sModelName As String
Dim sPathName As String
Dim varAlignment As Variant
Dim dataAlignment(11) As Double
Dim varViews As Variant
Dim dataViews(0) As String
Sub main()
Set swApp = Application.SldWorks
Set swModel = swApp.ActiveDoc
Set swPart = swModel
sModelName = swModel.GetPathName
sPathName = Left(sModelName, Len(sModelName) - 6) & "dxf"
dataAlignment(0) = 0#
dataAlignment(1) = 0#
dataAlignment(2) = 0#
dataAlignment(3) = 1#
dataAlignment(4) = 0#
dataAlignment(5) = 0#
dataAlignment(6) = 0#
dataAlignment(7) = 0#
dataAlignment(8) = -1#
dataAlignment(9) = 0#
dataAlignment(10) = 1#
dataAlignment(11) = 0#
varAlignment = dataAlignment
dataViews(0) = "*Top"
varViews = dataViews
swPart.ExportToDWG2 sPathName, sModelName, swExportToDWG_e.swExportToDWG_ExportAnnotationViews, True, varAlignment, False, False, 0, varViews
End Sub

Excel values to PDF form fields

objJSO.GetField(strField).Value = (strFieldVal) - That is the line I'm recieving a 'type mismatch' error on.
I've found the code base from "My Engineering World". It is an old post.
I'm selecting a static PDF form and trying to write values from an excel doc to the PDF form which contains the same field names. The excel doc has the field names in column c20-149 with the values for those fields in d20-149. I'm trying to write the values for those fields into the selected PDF form.
Option Explicit
Sub btnToPDF_Click()
Dim objAcroApp As Object
Dim objAcroAVDoc As Object
Dim objAcroPDDoc As Object
Dim objJSO As Object
Dim fd As Office.FileDialog
Dim strFile As String
Dim strField As String
Dim strFieldVal As String 'Used to hold the field value
Dim r As Long 'Used to increase row number for strfield name
'Disable screen flickering.
Application.ScreenUpdating = False
'Choose the Onsite Survey form you want to fill
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.AllowMultiSelect = False
.Title = "Please select the On-site survey PDF."
.Filters.Clear
.Filters.Add "PDF", "*.PDF"
'.Filters.Add "All Files", "*.*"
'If the .Show method returns False, the user clicked Cancel.
If .Show = True Then
strFile = .SelectedItems(1)
MsgBox (strFile)
End If
End With
'Initialize Acrobat by creating the App object.
Set objAcroApp = CreateObject("AcroExch.App")
'Check if the object was created.
If Err.Number <> 0 Then
MsgBox "Could not create the App object!", vbCritical, "Object error"
'Release the object and exit.
Set objAcroApp = Nothing
Exit Sub
End If
'Create the AVDoc object.
Set objAcroAVDoc = CreateObject("AcroExch.AVDoc")
'Check if the object was created.
If Err.Number <> 0 Then
MsgBox "Could not create the AVDoc object!", vbCritical, "Object error"
'Release the objects and exit.
Set objAcroAVDoc = Nothing
Set objAcroApp = Nothing
Exit Sub
End If
On Error GoTo 0
'Open the PDF file.
If objAcroAVDoc.Open(strFile, "") = True Then
'Set the PDDoc object.
Set objAcroPDDoc = objAcroAVDoc.GetPDDoc
'Set the JS Object - Java Script Object.
Set objJSO = objAcroPDDoc.GetJSObject
On Error GoTo 0
'Fill the form fields.
For r = 20 To 149
strField = Cells(r, 3)
strFieldVal = Cells(r, 4)
objJSO.GetField(strField).Value = CStr(strFieldVal)
If Err.Number <> 0 Then
'Close the form without saving the changes.
objAcroAVDoc.Close True
'Close the Acrobat application.
objAcroApp.Exit
'Inform the user about the error.
MsgBox "The field """ & strField & """ could not be found!", vbCritical, "Field error"
'Release the objects and exit.
Set objJSO = Nothing
Set objAcroPDDoc = Nothing
Set objAcroAVDoc = Nothing
Set objAcroApp = Nothing
Exit Sub
End If
Next r
'Save the form
objAcroPDDoc.Save 1, strFile
'Close the form without saving the changes.
'objAcroAVDoc.Close True
'Close the Acrobat application.
objAcroApp.Exit
'Release the objects.
Set objJSO = Nothing
Set objAcroPDDoc = Nothing
Set objAcroAVDoc = Nothing
Set objAcroApp = Nothing
'Enable the screen.
Application.ScreenUpdating = True
'Inform the user that forms were filled.
MsgBox "All forms were created successfully!", vbInformation, "Finished"
End If
MsgBox "Something bad happend :(...."
End Sub
OK... found my problem but I'm not sure how to trap the problem. I may not need to as I'm hoping I won't run into this problem. Hoping isn't the best strategy though... :)
My PDF form has fields of type numeric. All my test data in my value cells were alpha-numeric. Once I changed my quantity and cost cells to numeric values in my excel doc the form was written correctly.
Perhaps I can test for the PDF form field type. If it is numeric I'll log the field name and present a msgbox at the end of the operation that displays fields that could not be filled.
I did need to correct my objJSO line to '=strFieldVal'
I'm fairly certain you want...
strField = Cells(r, 3).Value
strFieldVal = Cells(r, 4).Value
objJSO.GetField(strField).Value = strFieldVal
...instead of the three corresponding lines you have.
Below is my final code. It includes basic error handling (more like logging). One problem I did have in this; If I was writing an alpha numeric string to the PDF field and the PDF field was numeric AND there wasn't a default value in the PDF field the PDF would throw and error that my code couldn't catch. As long as there was a default value in the PDF numeric field the error handler worked as planned. Feel free to make any comments. I'm guessing this looks like kindergarten work (maybe 1st grade??)
`Option Explicit
Sub btnToPDF_Click()
Dim objAcroApp As Object
Dim objAcroAVDoc As Object
Dim objAcroPDDoc As Object
Dim objJSO As Object
Dim fd As Office.FileDialog
Dim myWB As Workbook
Set myWB = ThisWorkbook
Dim ToPDFsh As Worksheet
Set ToPDFsh = myWB.Sheets("OSSDataDump")
Dim strFile As String
Dim strField As String
Dim strFieldVal As String 'Used to hold the field value
Dim msgFail As String
Dim colVal As Variant
Dim r As Integer 'Used to increase row number for strfield name
Dim e As Integer 'Used to track the number of errors
Dim colFail As Collection
Set colFail = New Collection
e = 0
'Disable screen flickering.
Application.ScreenUpdating = False
'Choose the Onsite Survey form you want to fill
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.AllowMultiSelect = False
.Title = "Please select the On-site survey PDF."
.Filters.Clear
.Filters.Add "PDF", "*.PDF"
'If the .Show method returns False, the user clicked Cancel.
If .Show = True Then
strFile = .SelectedItems(1)
End If
End With
'Initialize Acrobat by creating the App object.
Set objAcroApp = CreateObject("AcroExch.App")
'Check if the object was created.
If Err.Number <> 0 Then
MsgBox "Could not create the App object!", vbCritical, "Object error"
'Release the object and exit.
Set objAcroApp = Nothing
Exit Sub
End If
'Create the AVDoc object.
Set objAcroAVDoc = CreateObject("AcroExch.AVDoc")
'Check if the object was created.
If Err.Number <> 0 Then
MsgBox "Could not create the AVDoc object!", vbCritical, "Object error"
'Release the objects and exit.
Set objAcroAVDoc = Nothing
Set objAcroApp = Nothing
Exit Sub
End If
'Open the PDF file.
If objAcroAVDoc.Open(strFile, "") = True Then
'Set the PDDoc object.
Set objAcroPDDoc = objAcroAVDoc.GetPDDoc
'Set the JS Object - Java Script Object.
Set objJSO = objAcroPDDoc.GetJSObject
'Fill the form fields.
For r = 20 To 149
strField = ToPDFsh.Cells(r, 3).Value
strFieldVal = ToPDFsh.Cells(r, 4).Value
If strFieldVal = "" Then GoTo BlankVal
objJSO.GetField(strField).Value = strFieldVal
On Error GoTo ErrHandler
BlankVal:
Next r
'Save the form
objAcroPDDoc.Save 1, strFile
'Close the form without saving the changes.
'objAcroAVDoc.Close True
'Close the Acrobat application.
objAcroApp.Exit
'Release the objects.
Set objJSO = Nothing
Set objAcroPDDoc = Nothing
Set objAcroAVDoc = Nothing
Set objAcroApp = Nothing
'Enable the screen.
Application.ScreenUpdating = True
'Inform the user that forms were filled.
If e <> 0 Then
For Each colVal In colFail
msgFail = msgFail & colVal & vbNewLine
Next colVal
MsgBox "Not all fields were filled" & vbNewLine & "The follwoing fields failed:" & vbNewLine & msgFail, vbExclamation, "Finished"
Exit Sub
End If
MsgBox "On site survey was filled successfully!", vbInformation, "Finished"
End If
Exit Sub
ErrHandler:
e = e + 1
If e > 7 Then
MsgBox "Something Bad happend... :(" & vbNewLine & "Form not filled", vbCritical, "Failed"
GoTo ErrHandlerExit
End If
colFail.Add strField
Resume Next
Exit Sub
ErrHandlerExit:
'Close the form without saving the changes.
objAcroAVDoc.Close True
'Close the Acrobat application.
objAcroApp.Exit
'Release the objects and exit.
Set objJSO = Nothing
Set objAcroPDDoc = Nothing
Set objAcroAVDoc = Nothing
Set objAcroApp = Nothing
'Enable the screen.
Application.ScreenUpdating = True
Exit Sub
End Sub`

Export Table in Query to email VBA

I'm trying to export one of my queries to email using VBA in a table format. Similar to when you go to external data and click and E-Mail and it adds an attachment to outlook. Except I want it in the body. I put the following code in a button.
I found and made some changes to some code. This is what I have.
Private Sub Command5_Click()
Dim olApp As Object
Dim olItem As Variant
Dim db As DAO.Database
Dim rec As DAO.Recordset
Dim strQry As String
Dim aHead(1 To 4) As String
Dim aRow(1 To 4) As String
Dim aBody() As String
Dim lCnt As Long
'Create the header row
aHead(1) = "Part"
aHead(2) = "Description"
aHead(3) = "Qty"
aHead(4) = "Price"
lCnt = 1
ReDim aBody(1 To lCnt)
aBody(lCnt) = "<HTML><body><table border='2'><tr><th>" & Join(aHead, "</th> <th>") & "</th></tr>"
'Create each body row
strQry = "SELECT * From qry_email"
Set db = CurrentDb
Set rec = CurrentDb.OpenRecordset(strQry)
If Not (rec.BOF And rec.EOF) Then
Do While Not rec.EOF
lCnt = lCnt + 1
ReDim Preserve aBody(1 To lCnt)
aRow(1) = rec("Part")
aRow(2) = rec("Description")
aRow(3) = rec("Qty")
aRow(4) = rec("Price")
aBody(lCnt) = "<tr><td>" & Join(aRow, "</td><td>") & "</td></tr>"
rec.MoveNext
Loop
End If
aBody(lCnt) = aBody(lCnt) & "</table></body></html>"
'create the email
Set olApp = CreateObject("Outlook.application")
Set olItem = olApp.CreateItem(0)
olItem.Display
olItem.To = "email#email.com"
olItem.Subject = "Test E-mail"
olItem.HTMLBody = Join(aBody, vbNewLine)
olItem.Display
End Sub
When I run the code, I get a "Run-time error '3061' too few parameters. Expected 1."
If i click debug i get this highlighted in yellow. Anybody help would be greatly appreciated!
Edit
I tried a different approach which actually gave me the list in the body of the email. But it does it for the whole table instead of just the one record I want. This is what the SQL looks like of the query.
SELECT tblePMParts.[Part#], tblePMParts.PartDescription, tblePMParts.Qty, tblePMParts.Price
FROM tblePMParts
WHERE (((tblePMParts.WOID)=[Forms]![fmremail]![Text1]));
How would I go about adding the WHERE to the code below.
Private Sub Command4_Click()
'On Error GoTo Errorhandler
Dim olApp As Object
Dim olItem As Variant
Dim olatt As String
Dim olMailTem As Variant
Dim strSendTo As String
Dim strMsg As String
Dim strTo As String
Dim strcc As String
Dim rst As DAO.Recordset
Dim rs As DAO.Recordset
Dim db As DAO.Database
Dim qry As DAO.QueryDef
Dim fld As Field
Dim varItem As Variant
Dim strtable As String
Dim rec As DAO.Recordset
Dim strQry As String
strQry = "SELECT tblePMParts.[Part#], tblePMParts.PartDescription, tblePMParts.Qty, tblePMParts.Price " & _
"FROM tblePMParts; "
strSendTo = "test#email.com"
strTo = ""
strcc = ""
Set olApp = CreateObject("Outlook.application")
Set olItem = olApp.CreateItem(olMailTem)
olItem.Display
olItem.To = strTo
olItem.CC = strcc
olItem.Body = ""
olItem.Subject = "Please Quote the Following!"
Set db = CurrentDb
Set rec = CurrentDb.OpenRecordset(strQry)
If Not (rec.BOF And rec.EOF) Then
rec.MoveLast
rec.MoveFirst
intCount = rec.RecordCount
For intLoop = 1 To intCount
olItem.Body = olItem.Body & rec("[Part#]") & " - " & rec("PartDescription") & " - " & rec("Qty") & " - " & rec("Price")
rec.MoveNext
Next intLoop
End If
MsgBox "Completed Export"
Set olApp = Nothing
Set olItem = Nothing
Exit_Command21_Click:
Exit Sub
ErrorHandler:
MsgBox Err.Description, , Err.Number
Resume Exit_Command21_Click
End Sub
I got it working. Here is the code in case anybody needs it.
Private Sub Command5_Click()
Dim olApp As Object
Dim olItem As Variant
Dim db As DAO.Database
Dim rec As DAO.Recordset
Dim strQry As String
Dim aHead(1 To 3) As String
Dim aRow(1 To 3) As String
Dim aBody() As String
Dim lCnt As Long
'Create the header row
aHead(1) = "Part#"
aHead(2) = "Description"
aHead(3) = "Qty"
lCnt = 1
ReDim aBody(1 To lCnt)
aBody(lCnt) = "<HTML><body><table border='2'><tr><th>" & Join(aHead, "</th><th>") & "</th></tr>"
'Create each body row
strQry = "SELECT tblePMParts.[Part#], tblePMParts.PartDescription, tblePMParts.Qty, tblePMParts.Price " & _
"FROM tblePMParts " & _
"WHERE (((tblePMParts.WOID)=" & [Forms]![fmremail]![Text1] & "));"
Set db = CurrentDb
Set rec = CurrentDb.OpenRecordset(strQry)
If Not (rec.BOF And rec.EOF) Then
Do While Not rec.EOF
lCnt = lCnt + 1
ReDim Preserve aBody(1 To lCnt)
aRow(1) = rec("[Part#]")
aRow(2) = rec("PartDescription")
aRow(3) = rec("Qty")
aBody(lCnt) = "<tr><td>" & Join(aRow, "</td><td>") & "</td></tr>"
rec.MoveNext
Loop
End If
aBody(lCnt) = aBody(lCnt) & "</table></body></html>"
'create the email
Set olApp = CreateObject("Outlook.application")
Set olItem = olApp.CreateItem(0)
olItem.Display
olItem.To = "Email"
olItem.Subject = "Test E-mail"
olItem.HTMLBody = Join(aBody, vbNewLine)
olItem.Display
End Sub
Somewhere in your code, put a line that says
X = [Forms]![fmremail]![Text1]
Put a breakpoint in your code (hopefully you know how to do that?) on that line. When the code breaks, press F8 to step to the next line, and then type ?X in the Immediate Window. Or you can just hover your mouse over the line with the break point. The point is, you need to see what your code thinks [Forms]![fmremail]![Text1] is equal to. If it's null, you have a problem with your reference. In that case, you may need to add ".Value" or ".Text" to the end of it.
Another thing to check is your datatype for WOID. if it's text, you need to surround it with single quotes.
strQry = "SELECT tblePMParts.[Part#], tblePMParts.PartDescription, tblePMParts.Qty, tblePMParts.Price " & _
"FROM tblePMParts " & _
"WHERE (((tblePMParts.WOID)='" & [Forms]![fmremail]![Text1] & "'));"