更改活动表时我的调用代码失败

问题描述 投票:0回答:1

VBA 的新手,但已经做了一些研究,但无法在任何地方找到我的问题的答案。我在我的帐户程序的一个模块中有一个 Print to PDF sub,当我创建并保存“销售发票”工作表时效果很好,但是当我激活“零件交换”工作表并保存时它失败了。问题似乎与路径名和发票编号创建有关,因为我已经包含了一个消息框来尝试和调试,但是当我单步执行零件交换保存代码时该框是空的。 在工作表上,我在单元格 B4 (=Cell("Filename") 中有一个公式,我用它来测试哪个用户正在使用该工作簿。有时,当我更改工作表时,我确实遇到了这个公式没有更新的问题。

抱歉,我不能附上我的工作簿,因为它是私人的,但我可以附上几张测试工作表的图片

抱歉这么久,但我真的很沮丧。一点知识是一件危险的事情!!!

除了“放弃”之外的任何建议都将不胜感激。

销售发票表

1

零件交换表

2

Sub PrintPDF()

   Call Save_PDF
End Sub


Function Save_PDF() As Boolean
    Dim PathName As String
    Dim UserName As String
    Dim Inv_Number As Integer
    Dim svas As String
'Find the user name from Active sheet filename
    UserName = Range("B4") 'Gets the Cell("Filename") from the active sheet
    MsgBox Range("B4")
    
' Choose File Save Name from 2 options of different user accounts
   If InStr(UserName, "C:\Users\Martyn") Then
       PathName = Range("B3")       'User Martyns path to either Sales Invoice folder or Purchase
                                    'Invoice folder, depending on the sheet
    Else
        PathName = Range("B2")      'User Adams path as above
    End If
    
     Inv_Number = Range("H8")       'Gets the Invoice Number
     svas = PathName & "\" & Inv_Number & ".pdf" 'Full path to save PDF Both sheets save paths are correct
       
    MsgBox Dir(svas) 'Shows what the save path is this is fine in Sales Invoice but blank in Part Exchange 
        
    If Dir(svas) <> vbNullString Then 'Checks if the File is existing THIS IS A PROBLEM ON PART EXCHANGE
        If MsgBox("There is already a file of that name, do you wish to replace it?", vbYesNo, "Warning") = vbNo Then GoTo EndMacro
    End If
    
    
' Show PDF
    On Error GoTo OpenPDFError 'Always defaults to this line and debug goes to the following line when saving PART ;
'EXCHANGE SHEET
    ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=svas, Quality:=xlQualityStandard, IncludeDocProperties:=False, IgnorePrintAreas:=False, OpenAfterPublish:=True
    On Error GoTo 0
    
Save_File:
    MsgBox "A copy of this sheet has been successfully saved as a  .pdf  file: " & vbCrLf & vbCrLf & svas & _
       vbCrLf & "Please Review the .pdf document. If the document does NOT look good, adjust your printing parameters, and try again."
        
    Save_PDF = True
    GoTo EndMacro
    
OpenPDFError:
    MsgBox "Unable to save, there maybe an existing copy of invoice on file or open." & vbCrLf & "If you wish to" & _
    "overwrite this invoice then, please delet existing copy or close your PDF reader and try again", , "WARNING"
    
    Save_PDF = False
    
    
EndMacro:
End Function

谢谢 马丁

excel vba path filenames
1个回答
0
投票

公式

=Cell("Filename")
获取活动工作簿的文件名,无论它在哪个工作簿/工作表/单元格中。

既然你说你的 Debug MsgBox 有时会出现空白,这表明你打开了一个新的未保存的工作簿。如果该 wb 处于活动状态,则公式(所有这些,在任何工作簿中)将返回空白。

修复很简单:在所有公式中添加引用字段。

=Cell("Filename", B4)
© www.soinside.com 2019 - 2024. All rights reserved.