Как сохранить файл, который открывается? Как сохранить файл vba


vba - VBA: В Excel как сохранить документ Word как PDF?

У меня есть код, который копирует и вставляет данные из файла Excel в текстовый документ, как я могу получить этот текстовый документ для сохранения в виде PDF?

Мой код выглядит следующим образом:

Sub RetailerGraphs() Dim Location As String Dim Detail As String Worksheets("-Summary").Activate Range("AE9").Select While ActiveCell.Value <> "" ActiveCell.Offset(1, 0).Select Location = ActiveCell.Value Worksheets("Detail Summary").Activate Range("B7").Value = Location Dim objWord, objDoc As Object ActiveWindow.View = xlNormalView Set objWord = CreateObject("Word.Application") Set objDoc = objWord.Documents.Add Range("Ah50").Select While ActiveCell <> "" ActiveCell.Offset(1, 0).Select Detail = ActiveCell.Value Range("B11").Value = Detail Application.Wait (Now + TimeValue("0:00:05")) Range("A1:Z111").CopyPicture Appearance:=xlScreen, Format:=xlPicture objWord.Visible = True objWord.Selection.Paste objWord.Selection.TypeParagraph Set objSelection = objWord.Selection objSelection.InsertBreak (wdPageBreak) If ActiveCell.Value = "END" Then objWord.SaveAs2 "C:\Docs\MyDoc.pdf" End If Wend Worksheets("-Summary").Activate Wend End Sub

В пределах строк:

If ActiveCell.Value = "END" Then End If

Я попробовал следующий код, чтобы попытаться сохранить его как PDF:

objWord.ExportAsFixedFormat OutputFileName:="C:\wordtest.pdf", _ ExportFormat:=wdExportFormatPDF objWord.ExportAsFixedFormat OutputFileName:="C:\Documents and Settings\All Users\Desktop\YourFile.pdf", ExportFormat:=wdExportFormatPDF objDoc.ExportAsFixedFormat OutputFileName:="C:\Documents and Settings\All Users\Desktop\YourFile.pdf", ExportFormat:=wdExportFormatPDF

Но я получаю ошибку в строке, где я пытаюсь экспортировать ее как PDF, например objWord.SaveAs2 "C:\Docs\MyDoc.pdf":

Run-time error '438': Object doesn't support this property or method

Кто-то может помочь?

Примечание. Я убедился, что в ссылках отмечена "Библиотека объектов Microsoft Word 14.0", и я меняю местоположение на нужный каталог, а не на использование вышеперечисленного.

задан user4227507 24 авг. '15 в 19:45

источник поделиться

qaru.site

vba - VBA Excel Сохранить новый файл как дату активного файла

У меня есть имя файла "ABC XXXXXX XXX XXXX Report без XXX-XXX XXXXXXX Найдено 2017_11_01_071549"

Мой текущий код VBA разбивает листы и сохраняет каждый лист в качестве новой книги. Мне нужно, чтобы дата книги была такой же, как и исходная книга. Пример сверху 2017_11_01. В настоящее время сохраняется дата NAME_Today.

Мне также нужно указать папку ее сохранения на дату исходного файла. Пример 2017_11_01. Код в настоящее время сохраняется как "Книга".

Ниже приведен код. Я только запускаю: Sub OpenLatestFile()

Sub SaveShtsAsBook() ' ' SaveShtsAsBook Macro ' Splits out the sheets and saves them to their own file with date appended ' Dim ldate As String Dim SheetName1 As String Dim ParentFolder As String ldate = Format(Now(), "yyyy-mm-dd") Dim Sheet As Worksheet, SheetName$, MyFilePath$, N& ParentFolder = Left(ThisWorkbook.Name, Len(ThisWorkbook.Name) - 1) ParentFolder = Right(ParentFolder, 10) MyFilePath$ = ActiveWorkbook.Path & "\" & ParentFolder & "\" With Application .ScreenUpdating = False .DisplayAlerts = False ' End With On Error Resume Next '<< a folder exists 'need to change variable to the date here MkDir MyFilePath '<< create a folder For N = 2 To Sheets.Count Sheets(N).Activate SheetName = ActiveSheet.Name Cells.Copy SheetName1 = Range(A1).Value2 & ldate Workbooks.Add (xlWBATWorksheet) With ActiveWorkbook With .ActiveSheet .Paste .Name = SheetName [A1].Select End With tempstr = Cells(1, 1).Value2 openingParen = InStr(tempstr, "(") closingParen = InStr(tempstr, ")") SheetName1 = Mid(tempstr, openingParen + 1, closingParen - openingParen - 1) & "_" & ldate 'save book in this folder .SaveAs Filename:=MyFilePath & SheetName1 & ".xls" .Close SaveChanges:=True End With .CutCopyMode = False Next End With Sheet1.Activate ' End Sub Sub OpenLatestFile() ' ' OpenLatestFile Macro ' Opens the latest file specified in the specified folder ' 'Declare the variables Dim MyPath As String Dim MyFile As String Dim LatestFile As String Dim ArchivePath As String Dim LatestDate As Date Dim LMD As Date 'Specify the path to the folder 'MyPath = "c:\temp\excel" 'Make sure that the path ends in a backslash If Right(MyPath, 1) <> "\" Then MyPath = MyPath & "\" 'Get the first Excel file from the folder MyFile = Dir(MyPath & "*.xls", vbNormal) 'If no files were found, exit the sub If Len(MyFile) = 0 Then MsgBox "No files were found...", vbExclamation Exit Sub End If 'Loop through each Excel file in the folder Do While Len(MyFile) > 0 'Assign the date/time of the current file to a variable LMD = FileDateTime(MyPath & MyFile) 'If the date/time of the current file is greater than the latest 'recorded date, assign its filename and date/time to variables If LMD > LatestDate Then LatestFile = MyFile LatestDate = LMD End If 'Get the next Excel file from the folder MyFile = Dir Loop 'Open the latest file Workbooks.Open MyPath & LatestFile Call SaveShtsAsBook Application.Goto Reference:="OpenLatestFile" End Sub задан cmpmd2 09 дек. '17 в 1:41 источник поделиться

qaru.site

vba - Как сохранить файл, который открывается?

With ActiveSheet.Shapes.AddChart .ChartType = xlLineStacked .SetSourceData Source:=Range( _ "'cwapp5_MemCPU-Date-Mem'!$A:$A,'cwapp5_MemCPU-Date-Mem'!$B:$B") End With ChDir "D:\WayneCSV" ActiveWorkbook.SaveAs Filename:="D:\WayneCSV\" & *YourFileNameHere* &".xlsx", _ FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False

Замените имя файла YourFileNameHere именем, с которым вы хотите сохранить файл.

Или если вы хотите просто сохранить активную книгу с изменением

ActiveWorkbook.SaveAs Filename:=ThisWorkbook.FullName, _ FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False

Если вы хотите просмотреть всю возможную книгу или файл внутри "D:\WayneCSV", просто скажите мне, что вы имеете в виду, заставив make it work for all my files? погода, которая означает открытые листы excel, или книгу, или все файлы с расширением *.xlsx внутри "D:\WayneCSV"

Редактировать:

Dim StrFile As String StrFile = Dir("D:\WayneCSV\*.CSV") ' Looks up each file with CSV extension Do While Len(StrFile) > 0 ' While the file name is greater then nothing Workbooks.Open Filename:= "D:\WayneCSV\" & StrFile ' Open current workbook ActiveSheet.Shapes.AddChart.Select ' Add a chart ActiveChart.ChartType = xlLineStacked ' Add a chart type ActiveChart.SetSourceData Source:=Range("$A1:$B1", Range("$A1:$B1").End(xlDown)) ' Set the source range to be the used cells in A:B on the open worksheet With ActiveChart.Parent .Height = .Height*1.5 'Increase Height by 50% .Width = .Width*1.5 'Increase Width by 50% End With 'Note the setting of the source will only work while there are no skipped blank if you 'have empty rows in the source data please tell me and i can provide you with another ' way to get the information ActiveWorkbook.SaveAs Filename:="D:\WayneCSV\" & StrFile & ".xlsx", _ FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False ' Save file as excel xlsx with current files name ActiveWorkbook.Close ' Close when finished before opening next file this can be removed if you'd like to keep all open for review at the end of loop. StrFile = Dir ' Next File in Dir Loop

Дайте мне знать, если это работает, поскольку я не могу проверить без ваших папок и данных. Но это должно сработать.

qaru.site