Sub在运行时起作用,但在调用时不起作用? “范围类的选择方法失败”

时间:2018-09-24 10:03:56

标签: excel vba

此Sub有效。

Sub SalesPDF()
    Dim i As Integer, j As Integer, k As Integer, WdObj As Object, ws As Worksheet, EquitiesRow As Range, RowEnd As Range, BondRow As Range
    j = 0
    k = 0
    Set ws = Worksheets("PnL")
    Set SalesBrokerage = Worksheets("SalesBrokerage")
    SalesBrokerage.Cells(6 + k, 9).Value = MarketFinder(SalesBrokerage.Cells(6 + k, 10))
    k = k + 2
    Next i
    'blablabla...........
    SalesBrokerage.Range("b1,c1,f1").EntireColumn.AutoFit
    For i = 2 To 7
        SalesBrokerage.Columns(7 + i).ColumnWidth = SalesBrokerage.Columns(i).ColumnWidth
    Next i
    Call Excel2PDF
End Sub

我自己运行下面的代码时没有问题。

运行SalesPDF()并调用Excel2PDF()时收到错误消息

  

范围类的选择方法失败

SalesBrokerage.Range("B1:N" & SalesBrokerage.Cells(SalesBrokerage.Rows.Count, 2).End(xlUp).Offset(1, 0).Row).Select

Sub Excel2PDF()
Set SalesBrokerage = Worksheets("SalesBrokerage")
SalesBrokerage.Range("B1:N" & SalesBrokerage.Cells(SalesBrokerage.Rows.Count, 2).End(xlUp).Offset(1, 0).Row).Select
Selection.ExportAsFixedFormat Type:=xlTypePDF, Filename:="C:\Me.pdf" Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=True
End Sub

为什么在运行SalesPDF时不起作用?

1 个答案:

答案 0 :(得分:0)

类似ActiveWorkbookThisWorkbook的声音。当您不完全限定工作表/范围对象时,代码将假定它在活动工作簿中。

当您手动运行代码时,很有可能使该工作簿成为活动工作簿,因此它可以正常运行。

ActiveWorkbook =当前处于活动状态的工作簿(通常与用户可见的工作簿相同)

ThisWorkbook =执行代码所属的工作簿。


如果您的代码与您要引用的工作表位于同一工作簿中,则按以下方式对其进行限定:

Set SalesBrokerage = Worksheets("SalesBrokerage")

您还可以通过使用With块进行重构来使代码更具可读性:

With SalesBrokerage
    With .Range("B1:N" & .Cells(SalesBrokerage.Rows.Count, 2).End(xlUp).Offset(1, 0).Row)
        .ExportAsFixedFormat Type:=xlTypePDF, Filename:="C:\Me.pdf" Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=True
    End With
End With