Reputation: 196
I'm hoping someone can help me out. At work we make programs for CNC machines. these are word docs. These are saved in a folder named after the machine. i have made a userform where you can choose machine and fill in a program number. After clicking "OK" it will open all the programs needed. (this works succesfully) I then want to print the first page of all open programs. This is where is get stuck. See code below.
If Len(programbox.Value) = 1 Then zeros = "00000"
If Len(programbox.Value) = 2 Then zeros = "0000"
If Len(programbox.Value) = 3 Then zeros = "000"
If Len(programbox.Value) = 4 Then zeros = "00"
If Len(programbox.Value) = 5 Then zeros = "0"
If Len(programbox.Value) = 6 Then zeros = ""
Set wordapp = CreateObject("word.application")
If machinebox.Value = "CTX510" Then letter = "C"
If machinebox.Value = "CTX510" Then machinebox.Value = "CTX510\program"
If machinebox.Value = "Lu25" Then letter = "F"
If machinebox.Value = "LB45" Then letter = "N"
set objdoc1 = wordapp.documents.Open "\\path\Machine\" & machinebox.Value & "\" & letter & "1" & zeros & programmabox.Value & ".OPT"
set objdoc2 = wordapp.documents.Open "\\path\Machine\" & machinebox.Value & "\" & letter & "2" & zeros & programmabox.Value & ".OPT"
set objdoc3 = wordapp.documents.Open "\\path\Machine\" & machinebox.Value & "\" & letter & "3" & zeros & programmabox.Value & ".OPT"
objdoc1.printout
objdoc2.printout
objdoc3.printout
this prints out the whole doc. I have searched on the internet but can't find how i can change this to only the first page.
Upvotes: 2
Views: 1769
Reputation: 29421
you could try this little (untested) refactoring of your code:
Dim iLetter As Long
Dim letter As String
Dim objdoc As Object
Select Case machinebox.Value
Case "CTX510"
letter = "C"
machinebox.Value = "CTX510\program"
Case "Lu25"
letter = "F"
Case "LB45"
letter = "N"
End Select
With CreateObject("word.application")
For iLetter = 1 To 3
Set objdoc = .documents.Open("\\path\Machine\" & machinebox.Value & "\" & letter & iLetter & Format(programbox.Value, "000000") & ".OPT")
objdoc.PrintOut Pages:="1"
objdoc.Close False
Next iLetter
End With
where I:
used Format()
function to properly format a number from programbox
to a 6 digits one with leading zeros
used a Select Case .... End Select
block to switch between different machinebox.Value
cases
instantiated a "temporary" Word application object
used a loop from 1 to 3 instead of repeating three times the same statement
Upvotes: 2