vba 另存为文件而不提示输入文件名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8976880/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 12:27:44  来源:igfitidea点击:

Save as file without prompt for file name

excelvba

提问by macutan

I'm trying to create a PDF file without any user interface, other than clicking a button within the Excel file.

我正在尝试创建一个没有任何用户界面的 PDF 文件,而不是单击 Excel 文件中的按钮。

Using the below code, when the file is to be saved as with an automatically generated name, the code prompts for the filename, instead of grabbing it from the code.

使用下面的代码,当文件以自动生成的名称保存时,代码会提示输入文件名,而不是从代码中获取它。

I have a feeling that sendkeysis not working out.

我有一种感觉sendkeys是行不通的。

Sub PrinttoPDFTest()

    ActiveSheet.PageSetup.PrintArea = "$A:$F"
    With ActiveSheet.PageSetup
        .PrintTitleRows = ""
        .PrintTitleColumns = ""
    End With
    ActiveSheet.PageSetup.PrintArea = "$A:$F"
    With ActiveSheet.PageSetup
        .Orientation = xlLandscape
        .FitToPagesWide = 1
        .FitToPagesTall = 1
    End With

    ActiveWindow.SelectedSheets.PrintOut Copies:=1, ActivePrinter:="Adobe PDF on Ne04:", Collate:=True

    newHour = Hour(Now())
    newMinute = Minute(Now())
    newSecond = Second(Now()) + 5
    waitTime = TimeSerial(newHour, newMinute, newSecond)
    Application.Wait waitTime

    Filename = "C:\Temp\PDF\" & ActiveSheet.Range("DateSerial").Value & ".pdf"

    SendKeys Filename & "{Enter}", False

End Sub

回答by Tim

It would be simpler to use .ExportAsFixedFormat rather than .PrintOut, and just stack your requests (no delay code needed):

使用 .ExportAsFixedFormat 而不是 .PrintOut 会更简单,只需堆叠您的请求(不需要延迟代码):

Sub ExporttoPDF()

    Sheets("Sheet1").ExportAsFixedFormat xlTypePDF, "C:\Folder\Filename1.pdf"
    Sheets("Sheet2").ExportAsFixedFormat xlTypePDF, "C:\Folder\Filename2.pdf"

End Sub

Just replace the destinations and filenames, and this code should work fine. If you want to use a value in the sheet as part of a filename, then you can concatenate (&) like this:

只需替换目标和文件名,此代码应该可以正常工作。如果要将工作表中的值用作文件名的一部分,则可以像这样连接 (&):

Sheets("Sheet1").ExportAsFixedFormat xlTypePDF, "C:\Folder\" & Range("P10").Value & ".pdf"

Or store the filename in a variable and do it this way:

或者将文件名存储在一个变量中,然后这样做:

dim filename as string

filename = Range("P10").Value

Sheets("Sheet1").ExportAsFixedFormat xlTypePDF, filename

And it goes on and on...

它一直在继续……