ByRef argument type mismatch: - excel

ByRef argument type mismatch when running the fileconv.xla add-in in Excel 97.
The reason I need this to work is because I need to convert ~100 Lotus 1-2-3 files from wk* to xls.
The term highlighted in VBA when I compile is marked by double asteriks in the separated code:
Workbooks.Open Filename:=PathFile(**p_FileInfo**(i, 3), p_FileInfo(i, 4)), ReadOnly:=True, Password:="password"
Sub FinishSub()
Dim TestOpen As Boolean
Dim DirDest As String
Application.ScreenUpdating = False
CreateDir "wzkfpbdxwzkfpbdxwzkfpbdx"
If Not (DirCreated) Then
Application.ScreenUpdating = True
Exit Sub
End If
If Len(dlg.DropDowns("DriveDD").List(dlg.DropDowns("DriveDD").ListIndex)) <> 2 Then
DirDest = Right(dlg.DropDowns("DriveDD").List(dlg.DropDowns("DriveDD").ListIndex), _
Len(dlg.DropDowns("DriveDD").List(dlg.DropDowns("DriveDD").ListIndex)) - 3) & _
Right(FullPath, Len(FullPath) - 2)
Else
DirDest = dlg.DropDowns("DriveDD").List(dlg.DropDowns("DriveDD").ListIndex) & _
Right(FullPath, Len(FullPath) - 2)
End If
Set wbResult = Workbooks.Add
ActiveCell.Value = LookupString("File")
Range("B1").Value = LookupString("ConvertedTo")
Range("C1").Value = LookupString("Result")
Range("D1").Value = LookupString("Reason")
Range("A2").Select
k = 0
For i = 1 To CountFile
p_FileInfo(i, 5) = DirDest
If p_FileInfo(i, 7) = "yes" Then
k = k + 1
On Error GoTo ErrorOpen
Success = "True"
ErrorMsg = ""
SetWaitCursor True
If TestIfWorkbookIsOpen(p_FileInfo(i, 4)) Then Workbooks(p_FileInfo(i, 4)).Close saveChanges:=False
Application.StatusBar = LookupString("Opening") & p_FileInfo(i, 4) & "(" & k & "/" & CountFileToConvert & ")"
Application.DisplayAlerts = False
Workbooks.Open Filename:=PathFile(**p_FileInfo**(i, 3), p_FileInfo(i, 4)), ReadOnly:=True, Password:="password"
On Error GoTo 0
On Error Resume Next
Application.StatusBar = LookupString("Saving") & p_FileInfo(i, 6) & "(" & k & "/" & CountFileToConvert & ")"
' Check if the XLS filename already exists.
FindFileName
Workbooks(p_FileInfo(i, 4)).SaveAs Filename:=PathFile(p_FileInfo(i, 5), p_FileInfo(i, 6)), FileFormat:=xlNormal
'Application.StatusBar = False
Workbooks(p_FileInfo(i, 4)).Close saveChanges:=False
Workbooks(p_FileInfo(i, 6)).Close saveChanges:=False
SaveIsSuccess Success
SetWaitCursor False
On Error GoTo 0
End If
Next i
SaveIsSuccess "End"
Application.StatusBar = False
Application.ScreenUpdating = True
Exit Sub
ErrorOpen: ' Error-handling routine.
Select Case Err ' Evaluate Error Number.
Case 18
TestMsgBox = MsgBox(LookupString("UserInterruption", "AlertTable"), vbYesNo)
If TestMsgBox = vbYes Then
On Error Resume Next
Application.StatusBar = False
Workbooks(p_FileInfo(i, 4)).Close saveChanges:=False
Workbooks(p_FileInfo(i, 6)).Close saveChanges:=False
Application.ScreenUpdating = True
Exit Sub
On Error GoTo 0
Else
Resume Next
End If
Case 1004
SetWaitCursor False
Set dlg = ThisWorkbook.DialogSheets("Password")
dlg.DialogFrame.Characters.Text = p_FileInfo(i, 4)
If TryAgain = False Then
dlg.TextBoxes("PassTB").Text = LookupString("IsProtected", "AlertTable")
dlg.EditBoxes("PassEB").Text = ""
Else
dlg.TextBoxes("PassTB").Text = LookupString("InvalidPassword", "AlertTable")
End If
ShowTest = dlg.Show
Select Case ShowTest
Case True
Resume
Case False
Success = "False"
ErrorMsg = Error()
Resume Next
End Select
SetWaitCursor True
End Select
Application.StatusBar = False
End Sub

I assume you have this
Public Function PathFile(ByRef a As String, ByRef b As String)
PathFile = "C:\Bla.txt"
End Function
and p_FileInfo is an Array, so in this case you have to call the function like this:
Workbooks.Open Filename:=PathFile(CStr(p_FileInfo(i, 3)), CStr(p_FileInfo(i, 4))), ReadOnly:=True, Password:="password"
That should work if I am not misunderstand your question.

Related

Runtime error '5': Invalid procedure call or argument

I have used the following code before and worked as expected for a handful times. 4 hours later it did not work. I added the MsgBox "File: " and confirm the filename path is error free.
Option Explicit
Sub ExportAsPDF()
Dim Folder_Path As String
Dim NameOfWorkbook
NameOfWorkbook = Left(ActiveWorkbook.Name, (InStrRev(ActiveWorkbook.Name, ".", -1, vbTextCompare) - 1))
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Select Folder path"
If .Show = -1 Then Folder_Path = .SelectedItems(1)
End With
If Folder_Path = "" Then Exit Sub
Dim sh As Worksheet
Dim fn As String
For Each sh In ActiveWorkbook.Worksheets
fn = Folder_Path & Application.PathSeparator & NameOfWorkbook & "_" & sh.Name & ".pdf"
MsgBox "File: " & fn
sh.PageSetup.PaperSize = xlPaperA4
sh.PageSetup.LeftMargin = Application.InchesToPoints(0.5)
sh.PageSetup.RightMargin = Application.InchesToPoints(0.5)
sh.PageSetup.TopMargin = Application.InchesToPoints(0.5)
sh.PageSetup.BottomMargin = Application.InchesToPoints(0.5)
sh.PageSetup.HeaderMargin = Application.InchesToPoints(0.5)
sh.PageSetup.FooterMargin = Application.InchesToPoints(0.5)
sh.PageSetup.Orientation = xlPortrait
sh.PageSetup.CenterHorizontally = True
sh.PageSetup.CenterVertically = False
sh.PageSetup.FitToPagesTall = 1
sh.PageSetup.FitToPagesWide = 1
sh.PageSetup.Zoom = False
sh.ExportAsFixedFormat Type:=xlTypePDF, Filename:=fn, Quality:=xlQualityStandard, OpenAfterPublish:=True
Next
MsgBox "Done"
End Sub
Is there anything I missed?
Microsoft® Excel® for Microsoft 365 MSO (Version 2211 Build 16.0.15831.20220) 64-bit
If the ActiveWorkbook is new and was never stored, the workbook name is a generic name without any extension, eg Book1. In that case, InStrRev(ActiveWorkbook.Name, ".", -1, vbTextCompare) will return 0. Because you are nesting two commands, this 0 will be passed as parameter to the Left function, and Left(Name, 0) throws that runtime error 5.
Workaround: Write the result of InstrRev into an intermediate variable and check it. My advice is to avoid nested commands because it is much harder to check what exactly fails if there is an error because 0 is an invalid parameter.
Dim p As Long
p = InStrRev(ActiveWorkbook.Name, ".")
If p = 0 Then
NameOfWorkbook = ActiveWorkbook.Name
Else
NameOfWorkbook = Left(ActiveWorkbook.Name, p - 1)
End If
An alternative way to get the filename without extension is to use the FileSystemObject-method GetBaseName (will not work on a Mac)
nameOfWorkbook = CreateObject("Scripting.fileSystemObject").GetBasename(ActiveWorkbook.FullName)
Export Worksheets to Single PDFs
I could produce the error only when a worksheet was not visible (hidden or very hidden). The following deals with that and a few more issues.
Sub ExportAsPDF()
Const PROC_TITLE As String = "Export As PDF"
Const EXPORT_ONLY_VISIBLE_WORKSHEETS As Boolean = False
If ActiveWorkbook Is Nothing Then
MsgBox "No visible workbooks open.", vbExclamation, PROC_TITLE
Exit Sub
End If
Dim swb As Workbook: Set swb = ActiveWorkbook
If Len(swb.Path) = 0 Then
MsgBox "The workbook was not saved yet." & vbLf & vbLf _
& "Save it and try again.", vbExclamation, PROC_TITLE
Exit Sub
End If
Dim dFolderPath As String
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Select Folder path"
If .Show Then dFolderPath = .SelectedItems(1)
End With
If Len(dFolderPath) = 0 Then
MsgBox "No folder selected.", vbExclamation, PROC_TITLE
Exit Sub
End If
Dim swbBaseName As String: swbBaseName = swb.Name
swbBaseName = Left(swbBaseName, InStrRev(swbBaseName, ".") - 1)
Dim dFilePathLeft As String
dFilePathLeft = dFolderPath & Application.PathSeparator & swbBaseName & "_"
Dim sVisibility As XlSheetVisibility: sVisibility = xlSheetVisible
Dim sws As Worksheet
Dim dCount As Long
Dim dFilePath As String
Dim DoExport As Boolean
For Each sws In swb.Worksheets
With sws
If EXPORT_ONLY_VISIBLE_WORKSHEETS Then ' only visible
If .Visible = xlSheetVisible Then DoExport = True
Else ' all
If Not .Visible = xlSheetVisible Then
sVisibility = .Visible ' store
.Visible = xlSheetVisible ' make visible
End If
DoExport = True
End If
If DoExport Then
With .PageSetup
.PaperSize = xlPaperA4
.LeftMargin = Application.InchesToPoints(0.5)
.RightMargin = Application.InchesToPoints(0.5)
.TopMargin = Application.InchesToPoints(0.5)
.BottomMargin = Application.InchesToPoints(0.5)
.HeaderMargin = Application.InchesToPoints(0.5)
.FooterMargin = Application.InchesToPoints(0.5)
.Orientation = xlPortrait
.CenterHorizontally = True
.CenterVertically = False
.FitToPagesTall = 1
.FitToPagesWide = 1
.Zoom = False
End With
dFilePath = dFilePathLeft & .Name & ".pdf"
.ExportAsFixedFormat Type:=xlTypePDF, Filename:=dFilePath, _
Quality:=xlQualityStandard, OpenAfterPublish:=True
dCount = dCount + 1
DoExport = False ' reset for the next iteration
End If
If Not EXPORT_ONLY_VISIBLE_WORKSHEETS Then ' all
If Not sVisibility = xlSheetVisible Then
.Visible = sVisibility ' revert
sVisibility = xlSheetVisible ' reset
End If
End If
End With
Next sws
MsgBox dCount & " worksheet" & IIf(dCount = 1, "", "s") & " exported.", _
vbInformation, PROC_TITLE
End Sub

Looping for dynamic pictures

So I have created a dynamic selection list for excel using vba. see below
Below is the code
Private Sub Worksheet_Change(ByVal Target As Range)
On Error Resume Next
If Target.Address = "$A$2" Then
Call PanggilPhoto
End If
End Sub
Sub PanggilPhoto()
Application.ScreenUpdating = False
Dim myObj
Dim Foto
Set myObj = ActiveSheet.DrawingObjects
For Each Foto In myObj
If Left(Foto.Name, 7) = "Picture" Then
Foto.Select
Foto.Delete
End If
Next
Dim CommodityName1 As String, CommodityName2 As String, T As String
myDir = ThisWorkbook.Path & "\"
CommodityName1 = Range("A2")
T = ".png"
Range("C15").Value = CommodityName
On Error GoTo errormessage:
ActiveSheet.Shapes.AddPicture Filename:=myDir & CommodityName1 & T, _
linktofile:=msoFalse, savewithdocument:=msoTrue, Left:=190, Top:=10, Width:=140,
Height:=90
errormessage:If Err.Number = 1004 Then
Exit Sub
MsgBox "File does not exist." & vbCrLf & "Check the name of the Commodity!"
Range("A2").Value = ""
Range("C10").Value = ""
End If
Application.ScreenUpdating = True
End Sub
foto is a predefined data list in the sheet.
So the question is instead of doing it for one cell how can I create a loop of some sort to do it for multiple cells? I need it to import mulitple images on one macro run
found a solution
Private Sub Worksheet_Change(ByVal Target As Range)
On Error Resume Next
If Target.Address = "$A$2" Then
Call schedules
End If
End Sub
Sub schedules()
Worksheets("Picture").Activate
Application.ScreenUpdating = False
Dim myObj
Dim Foto
Set myObj = ActiveSheet.DrawingObjects
For Each Foto In myObj
If Left(Foto.Name, 7) = "Picture" Then
Foto.Select
Foto.Delete
End If
Next
Dim CommodityName1 As String, CommodityName2 As String, T1 As String, T2 As String
Dim i As Integer, j As Integer, k As Integer
j = 0
For i = 2 To 100
myDir = "C:\Users\User\Desktop\ESTIMATING SHEETS\test\rebar shapes" & "\"
CommodityName1 = Range("A" & i)
T1 = ".png"
On Error GoTo errormessage:
ActiveSheet.Shapes.AddPicture Filename:=myDir & CommodityName1 & T1, _
linktofile:=msoFalse, savewithdocument:=msoTrue, Left:=230, Top:=j, Width:=140, Height:=80
errormessage:
If Err.Number = 1004 Then
Exit Sub
MsgBox "File does not exist." & vbCrLf & "Check the name of the rebar!"
Range("A" & i).Value = ""
Range("C10").Value = ""
End If
Application.ScreenUpdating = True
i = i + 11
j = j + 190
Next i
End Sub

Trouble with this macro :(

I've been trying to program a special user login and Audit Trail, the login makes sheets display in custom order, then I still get
Error 1004: Method of Visible Object Failed.
Help me please :(
Macro 1 (I have 5 sheets in this book, each one has this macro in them):
Private Sub Worksheet_Deactivate()
Me.Name = "Información"
ThisWorkbook.Protect , True
Application.OnTime Now, "UnprotectBook"
End Sub
And Have this one in This Workbook:
Private Sub Workbook_Open()
Application.Visible = False
Sheet1.Visible = True
Sheet2.Visible = False
Sheet3.Visible = False
Sheet4.Visible = False
Sheet5.Visible = False
UF_log.Show
End Sub
Private Sub Workbook_Close()
Sheet1.Visible = False
Sheet2.Visible = False
Sheet3.Visible = False
Sheet4.Visible = False
Sheet5.Visible = False
End Sub
Private Sub Workbook_NewSheet(ByVal Sh As Object)
Application.DisplayAlerts = False
ActiveSheet.Delete
MsgBox "No se tiene permitido insertar nuevas hojas de cálculo", vbExclamation, "Alerta"
Application.DisplayAlerts = True
End Sub
UF log code:
Private Sub EnterButton_Click()
Dim Fila, final As Integer
Dim password As Variant
Dim DatoEncontrado
UsuarioExistente = Application.WorksheetFunction.CountIf(Sheets("Users").Range("A:A"), _
Me.TxtUser.Value)
Set Rango = Sheets("Users").Range("A:A")
If Trim(TxtUser.Text) = "" Then
MsgBox "Ingreso Usuario", vbExclamation, "Alerta"
TxtUser.SetFocus
Exit Sub
End If
If Trim(TxtPassword.Text) = "" Then
MsgBox "Ingreso Contraseña", vbExclamation, "Alerta"
TxtPassword.SetFocus
Exit Sub
End If
If UsuarioExistente = 0 Then
MsgBox "El usuario '" & Me.TxtUser & "' no existe", vbExclamation, "Alerta"
Exit Sub
End If
If UsuarioExistente = 1 Then
DatoEncontrado = Rango.Find(What:=Me.TxtUser.Value, MatchCase:=True).Address
Contra = CStr(Sheets("Users").Range(DatoEncontrado).Offset(0, 1).Value)
Estatus = CStr(Sheets("Users").Range(DatoEncontrado).Offset(0, 2).Value)
If Sheets("Users").Range(DatoEncontrado).Value = Me.TxtUser.Value And Contra = Me.TxtPassword.Value Then
MsgBox "Acceso correcto", vbExclamation, "Ok"
If Estatus = "Administrador" Then
Application.Visible = True
Sheet1.Visible = True
Sheet2.Visible = True
Sheet3.Visible = True
Sheet4.Visible = True
Sheet5.Visible = True
Application.CommandBars("Ply").Enabled = True
Call Desproteger
For Fila = 1 To 1000
If Sheet4.Cells(Fila, 1) = "" Then
final = Fila
Exit For
End If
Next
Sheet4.Cells(final, 1) = Application.UserName & " accessed via log in " & " at " & Time & " " & Date
Call Proteger
End
Else
If Estatus = "Fabricación" Then
Application.Visible = True
Sheet1.Visible = True
Sheet2.Visible = xlSheetVeryHidden
Sheet3.Visible = True
Sheet4.Visible = True
Sheet5.Visible = xlSheetVeryHidden
Application.CommandBars("Ply").Enabled = True
Call Desproteger
For Fila = 1 To 1000
If Sheet4.Cells(Fila, 1) = "" Then
final = Fila
Exit For
End If
Next
Sheet4.Cells(final, 1) = Application.UserName & " accessed via log in " & " at " & Time & " " & Date
Call Proteger
End
Else
Application.Visible = True
Sheet1.Visible = True
Sheet2.Visible = True
Sheet3.Visible = xlSheetVeryHidden
Sheet4.Visible = True
Sheet5.Visible = xlSheetVeryHidden
Application.CommandBars("Ply").Enabled = False
Call Desproteger
For Fila = 1 To 1000
If Sheet4.Cells(Fila, 1) = "" Then
final = Fila
Exit For
End If
Next
Sheet4.Cells(final, 1) = Application.UserName & " accessed via log in " & " at " & Time & " " & Date
Call Proteger
End
End If
End If
Else
MsgBox "Datos incorrectos, vuelva a intentar", vbExclamation, "Error"
End If
End If
End Sub
Private Sub ExitButton_Click()
End
End Sub

Updating form responses from one sheet to another

I created a data entry form in Excel.
I would like that input to be stored in another sheet (Table format).
Code I found online and modified:
Function ValidateForm() As Boolean
SellerSKU.BackColor = vbWhite
Description.BackColor = vbWhite
ValidateForm = True
If Trim(SellerSKU.Value) = "" Then
MsgBox "SKU can't be left blank.", vbOKOnly + vbInformation, "SKU"
SellerSKU.BackColor = vbRed
SellerSKU.Activate
ValidateForm = False
ElseIf Trim(Description.Value) = "" Then
MsgBox "Description can't be left blank.", vbOKOnly + vbInformation, "Description"
Description.BackColor = vbRed
Description.Activate
ValidateForm = False
End If
End Function
Private Sub CommandButton1_Click()
Application.ScreenUpdating = False
SellerSKU.Value = ""
SellerSKU.BackColor = vbWhite
Description.Value = ""
Description.BackColor = vbWhite
End Sub
Private Sub CommandButton2_Click()
Application.ScreenUpdating = False
Dim iRow As Long
iRow = Sheets("Reference Sheet (Order Hist)").Range("A1048576").End(xlUp).Row + 1
If ValidateForm = True Then
With ThisWorkbook.Sheets("Reference Sheet (Order Hist)")
.Range("A" & iRow).Value = SellerSKU.Value
.Range("C" & iRow).Value = Description.Value
End With
Call Reset
Else
Application.ScreenUpdating = False
Exit Sub
End If
Application.ScreenUpdating = True
End Sub
When I hit "Enter" on the data entry form, the table on the other sheet does not get updated.
Also is it possible to clear the form every time an entry has been successfully made?
This worked for me. Re-organized and removed some of the repetition...
Private Sub CommandButton2_Click()
Dim iRow As Long, valErrors As String
valErrors = ValidationErrors() 'checks the form
If Len(valErrors) = 0 Then
'no errors - add the data
With ThisWorkbook.Worksheets("Reference Sheet (Order Hist)")
iRow = .Cells(.Rows.Count, "A").End(xlUp).Row + 1
.Range("A" & iRow).Value = SellerSKU.Value
.Range("C" & iRow).Value = Description.Value
End With
ResetForm 'Call keyword is deprecated...
Else
MsgBox "One or more errors in form entries:" & vbLf & vbLf & valErrors, _
vbOKOnly + vbExclamation, "Check form data"
End If
End Sub
'check the form and return a listing of any errors
Function ValidationErrors() As String
Dim msg As String
CheckNonBlank SellerSKU, "SKU can't be left blank.", msg
CheckNonBlank Description, "Description can't be left blank.", msg
ValidationErrors = msg
End Function
'utility sub - check if a control has text, flag as error if missing,
' and add some text to the overall validation message
Sub CheckNonBlank(cntrl As Object, msgErr As String, ByRef msg As String)
Dim isErr As Boolean
isErr = Len(Trim(cntrl.Value)) = 0 'true if no content
ErrorFlag cntrl, isErr
If isErr And Len(msgErr) > 0 Then
msg = msg & IIf(Len(msg) > 0, vbLf, "") & msgErr 'append this error
End If
End Sub
Private Sub CommandButton1_Click()
ResetForm
End Sub
'clear textboxes and any error flags
Sub ResetForm()
SellerSKU.Value = ""
ErrorFlag SellerSKU, False
Description.Value = ""
ErrorFlag Description, False
End Sub
'flag a control as having a problem (pass False to second parameter to clear flag)
Sub ErrorFlag(cntrl As Object, Optional HasError As Boolean = True)
cntrl.BackColor = IIf(HasError, vbRed, vbWhite)
End Sub

VBA Set Print Area Based on Cell Reference

I put down together the following code. It basically loops through a path and converts all of the Excel workbooks into PDF.
I would like to setup the print area based on cell references. Cell C8 and D8
C8 = Column A - start of print area
D8 = Column M - end of print area
For example, I want the print area to start from column A - M. However, the current code prints everything, past column M
If settingsSheet.Range("C8").Value = vbNullString Or settingsSheet.Range("D8").Value = vbNullString Then
GoTo ABC
Else
reportColumnsAddr = settingsSheet.Range("C8").Value & ":" & settingsSheet.Range("D8").Value
Set reportSheet = Sheets(reportSheetName)
reportSheet.PageSetup.PrintArea = reportSheet.Columns(reportColumnsAddr).Address
End If
ABC:
Full code
Option Explicit
Private Sub CommandButton1_Click()
Dim MyFolder As String, MyFile As String
Dim StartTime As Double
Dim MinutesElapsed As String
Dim Filename As String
Dim Cell As String
Dim Counter As Long
If ThisWorkbook.Sheets("Sheet1").Range("C7").Value = vbNullString Then
MsgBox "Enter Tab Name"
Exit Sub
End If
With Application.FileDialog(msoFileDialogFolderPicker)
.AllowMultiSelect = False
.Title = "Select a Folder"
If .Show = True Then
MyFolder = .SelectedItems(1)
End If
If .SelectedItems.Count = 0 Then Exit Sub
Err.Clear
End With
Application.ScreenUpdating = False
Application.DisplayStatusBar = False
Application.EnableEvents = False
Application.Calculation = xlCalculationAutomatic
MyFile = Dir(MyFolder & "\", vbReadOnly)
StartTime = Timer
Do While MyFile <> ""
DoEvents
On Error GoTo 0
Workbooks.Open Filename:=MyFolder & "\" & MyFile, UpdateLinks:=False
Dim settingsSheet As Worksheet 'Source
Dim reportSheet As Worksheet 'To convert to PDF
Dim targetColumnsRange As Range 'feeds from source
Dim targetRowsRange As Range
Dim reportSheetName As String 'source sheet with the target's sheet name
Dim reportColumnsAddr As String
Dim reportRowsAddr As String
Dim WidthFit As String
Dim LengthFit As String
Set settingsSheet = ThisWorkbook.Worksheets("Sheet1") ' source
' Gather the report sheet's name
reportSheetName = settingsSheet.Range("C7").Value ' good
WidthFit = settingsSheet.Range("G8").Value
LengthFit = settingsSheet.Range("G9").Value
On Error Resume Next
Set reportSheet = Sheets(reportSheetName)
On Error GoTo 0
If reportSheet Is Nothing Then
MsgBox "No Sheet Named '" & reportSheetName & "' in This Workbook!"
Exit Sub
End If
If settingsSheet.Range("C8").Value = vbNullString Or settingsSheet.Range("D8").Value = vbNullString Then
GoTo ABC
Else
reportColumnsAddr = settingsSheet.Range("C8").Value & ":" & settingsSheet.Range("D8").Value
Set reportSheet = Sheets(reportSheetName)
reportSheet.PageSetup.PrintArea = reportSheet.Columns(reportColumnsAddr).Address
End If
ABC:
If WidthFit = "YES" Then
With reportSheet.PageSetup
.Zoom = False
.FitToPagesWide = 1
End With
End If
If LengthFit = "YES" Then
With reportSheet.PageSetup
.Zoom = False
.FitToPagesTall = 1
End With
End If
Filename = ActiveWorkbook.Name
Cell = Replace(Filename, ".xlsx", ".PDF")
reportSheet.Select
If settingsSheet.Range("J8").Value = "Landscape" Then
reportSheet.PageSetup.Orientation = xlLandscape
Else
reportSheet.PageSetup.Orientation = xlPortrait
End If
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
ThisWorkbook.Path & "\" & Cell, _
Quality:=xlQualityStandard, IncludeDocProperties:=True, _
IgnorePrintAreas:=True, OpenAfterPublish:=False
Counter = Counter + 1
0
Workbooks(MyFile).Close SaveChanges:=False
MyFile = Dir
Loop
Application.ScreenUpdating = True
Application.DisplayStatusBar = True
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
MinutesElapsed = Format((Timer - StartTime) / 86400, "hh:mm:ss")
MsgBox "Successfully Converted " & Counter & " Files in " & MinutesElapsed & " minutes", vbInformation
End Sub
Your error is you have set IgnorePrintAreas:=True, _ in reportSheet.ExportAsFixedFormat
That said, there are many other issues in your code:
Implicit ActiveWorkbook references
Unnecessary repetition of code in the loop
Case sensitive tests
Misleading variable names
Unnecessary use of GoTo
Malformed error handling
Could try to open non xlsx files
Incomplete checks of user Settings entry
Here's a refactor of your code
Private Sub CommandButton1_Click()
Dim MyFolder As String, MyFile As String
Dim StartTime As Double
Dim TimeElapsed As String
Dim Filename As String
Dim PdfFileName As String
Dim Counter As Long
Dim Orientation As XlPageOrientation
Dim settingsSheet As Worksheet 'Source
Dim reportSheet As Worksheet 'To convert to PDF
Dim targetColumnsRange As Range 'feeds from source
Dim targetRowsRange As Range
Dim reportSheetName As String 'source sheet with the target's sheet name
Dim reportColumnsAddr As String
Dim reportRowsAddr As String
Dim WidthFit As String
Dim LengthFit As String
Dim wb As Workbook
' Set a reference to the settings sheet
Set settingsSheet = ThisWorkbook.Worksheets("Sheet1") ' source
With settingsSheet
If .Range("C7").Value = vbNullString Then
MsgBox "Enter Tab Name"
Exit Sub
End If
If .Range("C8").Value = vbNullString Or .Range("D8").Value = vbNullString Then
MsgBox "Enter Valid Columns"
Exit Sub
End If
reportColumnsAddr = .Range("C8").Value & ":" & .Range("D8").Value
On Error Resume Next
Set targetColumnsRange = .Columns(reportColumnsAddr)
On Error GoTo 0
If targetColumnsRange Is Nothing Then
MsgBox "Enter Valid Columns"
Exit Sub
End If
Set targetColumnsRange = Nothing
reportSheetName = .Range("C7").Value ' good
WidthFit = .Range("G8").Value
LengthFit = .Range("G9").Value
Orientation = IIf(StrComp(.Range("J8").Value, "Landscape", vbTextCompare) = 0, xlLandscape, xlPortrait)
End With
With Application.FileDialog(msoFileDialogFolderPicker)
.AllowMultiSelect = False
.Title = "Select a Folder"
If .Show = True Then
MyFolder = .SelectedItems(1)
End If
If .SelectedItems.Count = 0 Then Exit Sub
Err.Clear
End With
Application.ScreenUpdating = False
Application.DisplayStatusBar = False
Application.EnableEvents = False
Application.Calculation = xlCalculationAutomatic
MyFile = Dir(MyFolder & "\*.xlsx", vbReadOnly)
StartTime = Timer()
Do While MyFile <> ""
DoEvents
On Error Resume Next
Set wb = Workbooks.Open(Filename:=MyFolder & "\" & MyFile, UpdateLinks:=False)
On Error GoTo 0
If wb Is Nothing Then
MsgBox "Failed to open " & MyFolder & "\" & MyFile
GoTo CleanUp
End If
Set reportSheet = Nothing
On Error Resume Next
Set reportSheet = wb.Worksheets(reportSheetName)
On Error GoTo 0
If reportSheet Is Nothing Then
MsgBox "No Sheet Named '" & reportSheetName & "' in This Workbook!"
GoTo CleanUp
End If
reportSheet.PageSetup.PrintArea = reportColumnsAddr
If StrComp(WidthFit, "YES", vbTextCompare) = 0 Then
With reportSheet.PageSetup
.Zoom = False
.FitToPagesWide = 1
End With
End If
If StrComp(LengthFit, "YES", vbTextCompare) = 0 Then
With reportSheet.PageSetup
.Zoom = False
.FitToPagesTall = 1
End With
End If
PdfFileName = Replace(wb.Name, ".xlsx", ".PDF")
reportSheet.PageSetup.Orientation = Orientation
reportSheet.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=ThisWorkbook.Path & "\" & PdfFileName, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
Counter = Counter + 1
wb.Close SaveChanges:=False
MyFile = Dir
Loop
CleanUp:
On Error Resume Next
wb.Close False
Application.ScreenUpdating = True
Application.DisplayStatusBar = True
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
TimeElapsed = Format((Timer() - StartTime) / 86400, "hh:mm:ss")
MsgBox "Successfully Converted " & Counter & " Files in " & TimeElapsed, vbInformation
End Sub

Resources