Vba word диалог сохранения

I have a vba macro that makes some changes to the current document and determines a filename that should be used for it — if the document isn’t saved as that filename yet the user should be prompted to do so (but should be able to alter the default setting).

I found two possibilities that both are not perfect (I’d need a mix of those two).

First approach:

Application.Dialogs(wdDialogFileSaveAs).Show

Opens the Save As dialog and lets you change the format and name of the file, but the default file name is the old filename or the title (up to the first special character like blank or -) of the document (in case it wasn’t saved yet — changing the title of the document is of little help as the suggested filename will contain -). Is it possible to change the initial filename shown in the Save As dialog?

Second approach:

Application.FileDialog(msoFileDialogSaveAs).InitialFileName = filename
Dim choice As Integer
choice = Application.FileDialog(msoFileDialogSaveAs).Show
If choice <> 0 Then
    filename = Application.FileDialog(msoFileDialogSaveAs).SelectedItems(1)
    Call ActiveDocument.SaveAs(filename:=filename, FileFormat:=wdFormatDocumentDefault)
End If

The FileDialog will choose a filename only, so we have to save it explicitely.
This approach will show the filename I want, but if the user changes the suffix to e.g .pdf the file will still be saved in the .docx format (using the suffix .pdf). I didn’t plan to have huge distinction of cases here for the rare case the user needs a different format than .docx. Is there an easy way to save the file in the correct format using this second approach?

0 / 0 / 0

Регистрация: 03.03.2012

Сообщений: 29

1

Открыть диалог сохранения файла

17.03.2012, 21:33. Показов 30823. Ответов 9


Студворк — интернет-сервис помощи студентам

Здравствуйте, господа программисты!
Скажите, пожалуйста, как средствами VBA можно открыть меню на сохранение программно созданной книги документа (изображение «сохранение).jpg » в прикрепленном файле)
У меня сделано вот так:
1) В исходной книге копируются 2 необходимых листа.
2) Выбранные листы помещаются в новую книгу, она сохраняется по указанному пути под фиксированным именем.
Файл прикрепил.
_____________________
Если у вас есть идеи и предложения, подскажите, пожалуйста, как можно программно вывести меню Eхcel (показанное в рисунке) на сохранение, в котором пользователь мог бы изменить пусть к папке, куда он хочет сохранить созданные документы и задать желаемое имя.

Миниатюры

Открыть диалог сохранения файла
 



0



Казанский

15136 / 6410 / 1730

Регистрация: 24.09.2011

Сообщений: 9,999

17.03.2012, 22:37

2

Лучший ответ Сообщение было отмечено как решение

Решение

Простейший случай

Visual Basic
1
Application.Dialogs(xlDialogSaveAs).Show

С предлагаемым именем и типом файла

Visual Basic
1
Application.Dialogs(xlDialogSaveAs).Show "предлагаемое_имя", xlExcel9795

С анализом действия пользователя

Visual Basic
1
2
If Not Application.Dialogs(xlDialogSaveAs).Show("предлагаемое_имя", xlExcel9795) Then _
    MsgBox "Книга не сохранена!", vbExclamation



5



0 / 0 / 0

Регистрация: 03.03.2012

Сообщений: 29

17.03.2012, 23:24

 [ТС]

3

Казанский, СПАСИБО Большое, первый из предложенных Вами вариантов, — то,что нужно ! а я то думал, там сочинение будет
а Вы не знаете,как закрыть/скрыть от пользователя созданную книгу или хотя бы её не высвечивать ? Чтобы только окно сохранения было видно и основная книга (откуда все копируется) ?



0



Казанский

15136 / 6410 / 1730

Регистрация: 24.09.2011

Сообщений: 9,999

18.03.2012, 01:10

4

В простейшем случае — перед командой копирования листов поставить

Visual Basic
1
Application.ScreenUpdating = False



0



strike383

616 / 0 / 1

Регистрация: 24.07.2013

Сообщений: 93

17.01.2014, 16:29

5

Visual Basic
1
2
If Not Application.Dialogs(xlDialogSaveAs).Show(Date & ".xlsx") Then _
        MsgBox "Книга не сохранена!", vbExclamation

А подскажите пожалуйста, как сюда добавить путь сохранения



0



0 / 0 / 0

Регистрация: 11.04.2018

Сообщений: 4

17.04.2018, 12:41

6

Цитата
Сообщение от Казанский
Посмотреть сообщение

«предлагаемое_имя», xlExcel9795

А как указать расширение сохраняемого файла PDF?



0



Казанский

15136 / 6410 / 1730

Регистрация: 24.09.2011

Сообщений: 9,999

17.04.2018, 14:43

7

seryga123, с помощью прямого вызова диалога — по-видимому, никак: сохранение в PDF производится не с помощью метода SaveAs, которому соответствует диалог Application.Dialogs(xlDialogSaveAs) , а с помощью метода ExportAsFixedFormat, соответствующего диалога которому я не нашел: https://msdn.microsoft.com/ru-… ment-lists
Поэтому сначала вызываем диалог выбора файла, потом сохраняем:

Visual Basic
1
2
3
4
5
6
7
Dim x
  x = Application.GetSaveAsFilename("c:tempmyfile", "PDF files (*.pdf), *.pdf") 'путь и предлагаемое имя файла
  If x <> False Then
    ActiveWorkbook.ExportAsFixedFormat Type:=xlTypePDF, Filename:=x _
      , Quality:=xlQualityStandard, IncludeDocProperties:=True _
      , IgnorePrintAreas:=False, OpenAfterPublish:=True
  End If



0



0 / 0 / 0

Регистрация: 11.04.2018

Сообщений: 4

17.05.2018, 09:46

8

Казанский, а не подскажите как в имя добавить переменную?
Я имею ввиду что-то вроде:

Код

 Application.Dialogs(xlDialogSaveAs).Show "name1" & "name2" & a, 51



0



15136 / 6410 / 1730

Регистрация: 24.09.2011

Сообщений: 9,999

17.05.2018, 10:15

9

seryga123, да, так. Вы попробовали?



0



0 / 0 / 0

Регистрация: 11.04.2018

Сообщений: 4

17.05.2018, 10:17

10

Да, конечно пробывал, но не работает!



0



Show All

SaveAs Method

Saves the specified document with a new name or format. Some of the arguments for this method correspond to the options in the Save As dialog box (File menu).

expression.SaveAs(FileName, FileFormat, LockComments, Password, AddToRecentFiles, WritePassword, ReadOnlyRecommended, EmbedTrueTypeFonts, SaveNativePictureFormat, SaveFormsData, SaveAsAOCELetter, Encoding, InsertLineBreaks, AllowSubstitutions, LineEnding, AddBiDiMarks)

expression    Required. An expression that returns a Document
object.

FileName    Optional Variant. The name for the document. The default is the current folder and file name. If the document has never been saved, the default name is used (for example, Doc1.doc). If a document with the specified file name already exists, the document is overwritten without the user being prompted first.

FileFormat    Optional Variant. The format in which the document is saved. Can be any WdSaveFormat
constant. To save a document in another format, specify the appropriate value for the SaveFormat
property of the FileConverter object.

WdSaveFormat can be one of these WdSaveFormat constants.
wdFormatDocument Saves as a Microsoft Word document. Default.
wdFormatDOSText Saves text without formatting. Converts all section breaks, page breaks, and new line characters to paragraph marks. Uses the ANSI character set. Use this format to share documents between Word and DOS-based programs.
wdFormatDOSTextLineBreaks Saves text without formatting. Converts all line breaks, section breaks, and page breaks to paragraph marks. Use this format when you want to maintain line breaks, for example, when transferring documents to an electronic mail system.
wdFormatEncodedText Saves as an encoded text file. Use the Encoding argument to specify the code page to use.
wdFormatFilteredHTML Saves text with HTML tags with minimal cascading style sheet formatting. The resulting document can be viewed in a Web browser.
wdFormatHTML Saves all text and formatting with HTML tags so that the resulting document can be viewed in a Web browser.
wdFormatRTF Saves all formatting. Converts formatting to instructions that other programs, including compatible Microsoft programs, can read and interpret.
wdFormatTemplate Saves as a Word template.
wdFormatText Saves text without formatting. Converts all section breaks, page breaks, and new line characters to paragraph marks. Uses the ANSI character set. Use this format if the destination program cannot read any of the other available file formats.
wdFormatTextLineBreaks Saves text without formatting. Converts all line breaks, section breaks, and page breaks to paragraph marks. Use this format when you want to maintain line breaks, for example, when transferring documents to an electronic mail system.
wdFormatUnicodeText Saves as a Unicode text file. Converts text between common character encoding standards, including Unicode 2.0, Mac OS, Windows, EUC and ISO-8859 series.
wdFormatWebArchive Saves the text, images, and formatting as a single-file Web page.
wdFormatXML Saves text and formatting using Extensible Markup Language (XML) and the Word XML schema.
Other File Types To save in a file type for which there isn’t a constant, use the FileConverters
object to obtain the SaveFormat
property; then set the FileFormat argument to the value of the SaveFormat property.

LockComments    Optional Variant. True to lock the document for comments. The default is False.

Password    Optional Variant. A password string for opening the document. (See Remarks below.)

AddToRecentFiles    Optional Variant. True to add the document to the list of recently used files on the File menu. The default is True.

WritePassword    Optional Variant. A password string for saving changes to the document. (See Remarks below.)

ReadOnlyRecommended    Optional Variant. True to have Microsoft Word suggest read-only status whenever the document is opened. The default is False.

EmbedTrueTypeFonts    Optional Variant. True to save TrueType fonts with the document. If omitted, the EmbedTrueTypeFonts    argument assumes the value of the EmbedTrueTypeFonts
property.

SaveNativePictureFormat    Optional Variant. If graphics were imported from another platform (for example, Macintosh), True to save only the Windows version of the imported graphics.

SaveFormsData    Optional Variant. True to save the data entered by a user in a form as a data record.

SaveAsAOCELetter    Optional Variant. If the document has an attached mailer, True to save the document as an AOCE letter (the mailer is saved).

Encoding   Optional MsoEncoding. The code page, or character set, to use for documents saved as encoded text files. The default is the system code page.

MsoEncoding can be one of these MsoEncoding constants.
msoEncodingArabic
msoEncodingArabicASMO
msoEncodingArabicAutoDetect Not used with this method.
msoEncodingArabicTransparentASMO
msoEncodingAutoDetect Not used with this method.
msoEncodingBaltic
msoEncodingCentralEuropean
msoEncodingCyrillic
msoEncodingCyrillicAutoDetect Not used with this method.
msoEncodingEBCDICArabic
msoEncodingEBCDICDenmarkNorway
msoEncodingEBCDICFinlandSweden
msoEncodingEBCDICFrance
msoEncodingEBCDICGermany
msoEncodingEBCDICGreek
msoEncodingEBCDICGreekModern
msoEncodingEBCDICHebrew
msoEncodingEBCDICIcelandic
msoEncodingEBCDICInternational
msoEncodingEBCDICItaly
msoEncodingEBCDICJapaneseKatakanaExtended
msoEncodingEBCDICJapaneseKatakanaExtendedAndJapanese
msoEncodingEBCDICJapaneseLatinExtendedAndJapanese
msoEncodingEBCDICKoreanExtended
msoEncodingEBCDICKoreanExtendedAndKorean
msoEncodingEBCDICLatinAmericaSpain
msoEncodingEBCDICMultilingualROECELatin2
msoEncodingEBCDICRussian
msoEncodingEBCDICSerbianBulgarian
msoEncodingEBCDICSimplifiedChineseExtendedAndSimplifiedChinese
msoEncodingEBCDICThai
msoEncodingEBCDICTurkish
msoEncodingEBCDICTurkishLatin5
msoEncodingEBCDICUnitedKingdom
msoEncodingEBCDICUSCanada
msoEncodingEBCDICUSCanadaAndJapanese
msoEncodingEBCDICUSCanadaAndTraditionalChinese
msoEncodingEUCChineseSimplifiedChinese
msoEncodingEUCJapanese
msoEncodingEUCKorean
msoEncodingEUCTaiwaneseTraditionalChinese
msoEncodingEuropa3
msoEncodingExtAlphaLowercase
msoEncodingGreek
msoEncodingGreekAutoDetect Not used with this method.
msoEncodingHebrew
msoEncodingHZGBSimplifiedChinese
msoEncodingIA5German
msoEncodingIA5IRV
msoEncodingIA5Norwegian
msoEncodingIA5Swedish
msoEncodingISO2022CNSimplifiedChinese
msoEncodingISO2022CNTraditionalChinese
msoEncodingISO2022JPJISX02011989
msoEncodingISO2022JPJISX02021984
msoEncodingISO2022JPNoHalfwidthKatakana
msoEncodingISO2022KR
msoEncodingISO6937NonSpacingAccent
msoEncodingISO885915Latin9
msoEncodingISO88591Latin1
msoEncodingISO88592CentralEurope
msoEncodingISO88593Latin3
msoEncodingISO88594Baltic
msoEncodingISO88595Cyrillic
msoEncodingISO88596Arabic
msoEncodingISO88597Greek
msoEncodingISO88598Hebrew
msoEncodingISO88599Turkish
msoEncodingJapaneseAutoDetect Not used with this method.
msoEncodingJapaneseShiftJIS
msoEncodingKOI8R
msoEncodingKOI8U
msoEncodingKorean
msoEncodingKoreanAutoDetect Not used with this method.
msoEncodingKoreanJohab
msoEncodingMacArabic
msoEncodingMacCroatia
msoEncodingMacCyrillic
msoEncodingMacGreek1
msoEncodingMacHebrew
msoEncodingMacIcelandic
msoEncodingMacJapanese
msoEncodingMacKorean
msoEncodingMacLatin2
msoEncodingMacRoman
msoEncodingMacRomania
msoEncodingMacSimplifiedChineseGB2312
msoEncodingMacTraditionalChineseBig5
msoEncodingMacTurkish
msoEncodingMacUkraine
msoEncodingOEMArabic
msoEncodingOEMBaltic
msoEncodingOEMCanadianFrench
msoEncodingOEMCyrillic
msoEncodingOEMCyrillicII
msoEncodingOEMGreek437G
msoEncodingOEMHebrew
msoEncodingOEMIcelandic
msoEncodingOEMModernGreek
msoEncodingOEMMultilingualLatinI
msoEncodingOEMMultilingualLatinII
msoEncodingOEMNordic
msoEncodingOEMPortuguese
msoEncodingOEMTurkish
msoEncodingOEMUnitedStates
msoEncodingSimplifiedChineseAutoDetect Not used with this method.
msoEncodingSimplifiedChineseGBK
msoEncodingT61
msoEncodingTaiwanCNS
msoEncodingTaiwanEten
msoEncodingTaiwanIBM5550
msoEncodingTaiwanTCA
msoEncodingTaiwanTeleText
msoEncodingTaiwanWang
msoEncodingThai
msoEncodingTraditionalChineseAutoDetect Not used with this method.
msoEncodingTraditionalChineseBig5
msoEncodingTurkish
msoEncodingUnicodeBigEndian
msoEncodingUnicodeLittleEndian
msoEncodingUSASCII
msoEncodingUTF7
msoEncodingUTF8
msoEncodingVietnamese
msoEncodingWestern

InsertLineBreaks   Optional Variant. If the document is saved as a text file, True to insert line breaks at the end of each line of text.

AllowSubstitutions   Optional Variant. If the document is saved as a text file, True allows Word to replace some symbols with text that looks similar. For example, displaying the copyright symbol as (c). The default is False.

LineEnding   Optional Variant. The way Word marks the line and paragraph breaks in documents saved as text files. Can be any WdLineEndingType
constant.

WdLineEndingType can be one of these WdLineEndingType constants.
wdCRLF Default.
wdCROnly
wdLFCR Not used with this method.
wdLFOnly Not used with this method.
wdLSPS Not used with this method.

AddBiDiMarks   Optional Variant. True adds control characters to the output file to preserve bi-directional layout of the text in the original document.

Remarks

Security   Avoid using hard-coded passwords in your applications. If a password is required in a procedure, request the password from the user, store it in a variable, and then use the variable in your code. For recommended best practices on how to do this, see Security Notes for Microsoft Office Solution Developers.

Example

This example saves the active document as Test.rtf in rich-text format (RTF).

    Sub SaveAsRTF()
    ActiveDocument.SaveAs FileName:="Text.rtf", _
        FileFormat:=wdFormatRTF
End Sub
  

This example saves the active document in text-file format with the file extension «.txt».

    Sub SaveAsTextFile()
    Dim strDocName As String
    Dim intPos As Integer

    'Find position of extension in filename
    strDocName = ActiveDocument.Name
    intPos = InStrRev(strDocName, ".")

    If intPos = 0 Then

        'If the document has not yet been saved
        'Ask the user to provide a filename
        strDocName = InputBox("Please enter the name " & _
            "of your document.")
    Else

        'Strip off extension and add ".txt" extension
        strDocName = Left(strDocName, intPos - 1)
        strDocName = strDocName & ".txt"
    End If

    'Save file with new extension
    ActiveDocument.SaveAs FileName:=strDocName, _
        FileFormat:=wdFormatText
End Sub
  

This example loops through all the installed converters, and if it finds the WordPerfect 6.0 converter, it saves the active document using the converter.

    Sub SaveWithConverter()

    Dim cnvWrdPrf As FileConverter

    'Look for WordPerfect file converter
    'And save document using the converter
    'For the FileFormat converter value
    For Each cnvWrdPrf In Application.FileConverters
        If cnvWrdPrf.ClassName = "WrdPrfctWin" Then
            ActiveDocument.SaveAs FileName:="MyWP.doc", _
                FileFormat:=cnvWrdPrf.SaveFormat
        End If
    Next cnvWrdPrf

End Sub
  

This example illustrates a procedure that saves a document with a password.

    Sub SaveWithPassword(docCurrent As Document, strPWD As String)
    With docCurrent
        .SaveAs WritePassword:=strPWD
    End With
End Sub
  

application filedialog featured

Often in VBA we need to ask the users to select files or directories before we execute the actual functionality of our macro. Welcome to the VBA Open file dialog post. Today we will learn how to use the Application.FileDialog, to understand the various msoFileDialogFilePicker file dialog picking options and how to properly manage these dialogs.

Here is a simple example of a VBA File Dialog:

Dim fDialog As FileDialog
Set fDialog = Application.FileDialog(msoFileDialogFilePicker)

'Show the dialog. -1 means success!
If fDialog.Show = -1 Then
   Debug.Print fDialog.SelectedItems(1) 'The full path to the file selected by the user
End If

Application FileDialog function

Before we start let’s understand the Application.FileDialog function.

The Application.FileDialog has the following syntax:

Application.FileDialog( fileDialogType as MsoFileDialogType )

Parameter

MsoFileDialogType
An enumeration defining the type of file dialog to open. It has the following values:

Value Description
msoFileDialogOpen Open dialog box
msoFileDialogSaveAs Save As dialog box
msoFileDialogFilePicker File picker dialog box
msoFileDialogFolderPicker Folder picker dialog box

Properties and functions

FileDialog properties

Property Description
AllowMultiSelect Allow to select more than one file or folder
ButtonName Text displayed on the action button of a file dialog box
DialogType Change the MsoFileDialogType (see above)
Filter Set a file filter to filter file types user can select
InitialFileName The initial path to be opened e.g. C:
InitialView The initial file view. Can be one of the following:

  • msoFileDialogViewDetails
  • msoFileDialogViewLargeIcons
  • msoFileDialogViewList
  • msoFileDialogViewPreview
  • msoFileDialogViewProperties
  • msoFileDialogViewSmallIcons
  • msoFileDialogViewThumbnail
  • msoFileDialogViewWebView
SelectedItems Collection of type FileDialogSelectedItems with all selected items
Title Title of the Open file dialog window

Select files – msoFileDialogFilePicker

select file filedialogThe msoFileDialogFilePicker dialog type allows you to select one or more files.

Select single files

The most common select file scenario is asking the user to select a single file. The code below does just that:

Dim fDialog As FileDialog, result As Integer
Set fDialog = Application.FileDialog(msoFileDialogFilePicker)
    
'Optional: FileDialog properties
fDialog.AllowMultiSelect = False
fDialog.title = "Select a file"
fDialog.InitialFileName = "C:"
'Optional: Add filters
fDialog.Filters.Clear
fDialog.Filters.Add "Excel files", "*.xlsx"
fDialog.Filters.Add "All files", "*.*"

'Show the dialog. -1 means success!
If fDialog.Show = -1 Then
   Debug.Print fDialog.SelectedItems(1)
End If

'Result: C:somefile.xlsx

Select multiple files

Quite common is a scenario when you are asking the user to select one or more files. The code below does just that. Notice that you need to set AllowMultiSelect to True.

Dim fDialog As FileDialog, result As Integer
Set fDialog = Application.FileDialog(msoFileDialogFilePicker)
    
'IMPORTANT!
fDialog.AllowMultiSelect = True

'Optional FileDialog properties
fDialog.title = "Select a file"
fDialog.InitialFileName = "C:"
'Optional: Add filters
fDialog.Filters.Clear
fDialog.Filters.Add "Excel files", "*.xlsx"
fDialog.Filters.Add "All files", "*.*"

'Show the dialog. -1 means success!
If fDialog.Show = -1 Then
  For Each it In fDialog.SelectedItems
    Debug.Print it
  Next it
End If

'Results:
'C:somefile.xlsx
'C:somefile1.xlsx
'C:somefile2.xlsx

Select folder – msoFileDialogFilePicker

select folder application.filedialogSelecting a folder is more simple than selecting files. However only a single folder can be select within a single dialog window.

Select folder example

The dialog below will ask the user to select a folder:

Set fDialog = Application.FileDialog(msoFileDialogFolderPicker) 'Important we use msoFileDialogFolderPicker instead of (...)FilePicker

'Optional: Properties
fDialog.title = "Select a folder"
fDialog.InitialFileName = "C:"

If fDialog.Show = -1 Then
  Debug.Print fDialog.SelectedItems(1)
End If

The msoFileDialogFolderPicker dialog allows you to only select a SINGLE folder and obviously does not support file folders

Open file – msoFileDialogOpen

file open application.filedialogOpening files is much more simple as it usually involves a single file. The only difference between the behavior between Selecting and Opening files are button labels.

Open file example

The dialog below will ask the user to select a file to open:

Dim fDialog As FileDialog, result As Integer, it As Variant
Set fDialog = Application.FileDialog(msoFileDialogOpen)
    
'Optional: FileDialog properties
fDialog.title = "Select a file"
fDialog.InitialFileName = "C:"
    
'Optional: Add filters
fDialog.Filters.Clear
fDialog.Filters.Add "All files", "*.*"
fDialog.Filters.Add "Excel files", "*.xlsx"
  
If fDialog.Show = -1 Then
  Debug.Print fDialog.SelectedItems(1)
End If

Save file – msoFileDialogSaveAs

saveas application.filedialogSaving a file is similarly easy, and also only the buttons are differently named.

The save file dialog will in fact not save any files! It will just allow the user to select a filename for the file. You need to open the files for reading / writing yourself. Check out my post on how to write files in VBA

Save file example

The dialog below will ask the user to select a path to which a files is to be saved:

Dim fDialog As FileDialog, result As Integer, it As Variant
Set fDialog = Application.FileDialog(msoFileDialogSaveAs)

'Optional: FileDialog properties
fDialog.title = "Save a file"
fDialog.InitialFileName = "C:"

If fDialog.Show = -1 Then
  Debug.Print fDialog.SelectedItems(1)
End If

The msoFileDialogSaveAs dialog does NOT support file filters

FileDialog Filters

One of the common problems with working with the Application.FileDialog is setting multiple file filters. Below some common examples of how to do this properly. To add a filter for multiple files use the semicolor ;:

Dim fDialog As FileDialog
Set fDialog = Application.FileDialog(msoFileDialogOpen)
'...
'Optional: Add filters
fDialog.Filters.Clear
fDialog.Filters.Add "All files", "*.*"
fDialog.Filters.Add "Excel files", "*.xlsx;*.xls;*.xlsm"
fDialog.Filters.Add "Text/CSV files", "*.txt;*.csv"
'...

Be sure to clear your list of filters each time. The FileDialog has its nuisances and often filters are not cleared automatically. Hence, when creating multiple dialogs you might see filters coming from previous executed dialogs if not cleared and re-initiated properly.

The open file dialog will in fact not open any files! It will just allow the user to select files to open. You need to open the files for reading / writing yourself. Check out my posts:

  • Read file in VBA
  • Write file in VBA

JoAnn


  • #1

Hi,

I’m creating a FileSaveAs macro to replace Word’s default command so I can
perform a customized save as under certain conditions.

To execute Word’s default FileSaveAs, I tried entering the code
ActiveDocument.SaveAs — however, this does not display Word’s File Save As
dialog box.

How can I get Word’s default Save As behavior (dialog box to prompt them for
name/directory/filetype) via VBA?

Thanks for your help!

Advertisements

Jay Freedman


  • #2

JoAnn said:

Hi,

I’m creating a FileSaveAs macro to replace Word’s default command so I can
perform a customized save as under certain conditions.

To execute Word’s default FileSaveAs, I tried entering the code
ActiveDocument.SaveAs — however, this does not display Word’s File Save As
dialog box.

How can I get Word’s default Save As behavior (dialog box to prompt them for
name/directory/filetype) via VBA?

Thanks for your help!

Hi Joann,

You do this:

Dialogs(wdDialogFileSaveAs).Show

or, if you don’t want the dialog to actually save the file but just
pass back to you the name the user chose, you do this:

With Dialogs(wdDialogFileSaveAs)
If .Display = -1 Then
myFile = .Name
End If
End With

For more, see http://word.mvps.org/FAQs/MacrosVBA/WordDlgHelp.htm and
http://word.mvps.org/FAQs/MacrosVBA/SetDefFilename.htm.

Уважаемые форумчане, вынужден обратиться с вопросом следующего характера:
С Вашей же помощью мне удалось из кусочков составить код, который при запуске осуществляет копирование данных с листа Excelи вставляет эти данные на вновь созданный лист Word.

Но мне не удается реализовать заключительный этап своего замысла – мне необходимо вновь созданный файл Word предложить пользователю сохранить в исходной папке (папка где размещается файл Excel) с заготовкой имени файла. При этом команда на сохранение должна отдаваться именно пользователем, а не сохранятся автоматически.

Очень хочу реализовать свой замысел именно следующим образом:
1.       Запуск макроса из книги Excel.
2.       Копирование данных.
3.       Создание листа Word.
4.       Вставка данных на лист Word.
5.       Вызов диалогового окна для сохранения файла с возможностью редактировать имя файла перед его сохранением. Путь сохранения (по умолчанию) должен быть предложен в папку, в которой сохранен Исходный файл Excel. – здесь мне требуется Ваша помощь!!!
6.       После сохранения Пользователем файла завершение работы макроса.

Мне удалось найти решение этой задачи, но только в коде VBA для Word. Перечитал очень много тем, но так и не смог перевести данный код на понятный язык для Excel

Код
Sub MyFileSave() ' если запускать данный код из Word, то он полностью решает мою проблему
Dim sPath As String
 
sPath = ActiveDocument.Path & ""
'sPath = ActiveWorkbook.Path & "" ' для Excel, сэтимвродеудалосьразобраться
 
With Dialogs(wdDialogFileSaveAs) ' а вот здесь при запуске макроса вылетает ошибка.
.Name = sPath & "Переченьработ_" & Left(ActiveDocument.Paragraphs(2).Range.Text, Len(ActiveDocument.Paragraphs(2).Range.Text) - 1)
.Show
End With
End Sub

Очень прошу Вас помочь мне!
Спасибо!

Данная тема близка к моей проблеме

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

Пример прилагаю.

    msm.ru

    Нравится ресурс?

    Помоги проекту!

    Популярные разделы FAQ:    user posted image Общие вопросы    user posted image Особенности VBA-кода    user posted image Оптимизация VBA-кода    user posted image Полезные ссылки


    1. Старайтесь при создании темы указывать в заголовке или теле сообщения название офисного приложения и (желательно при работе с Office 95/97/2000) его версию. Это значительно сократит количество промежуточных вопросов.
    2. Формулируйте вопросы как можно конкретнее, вспоминая (хотя бы иногда) о правилах ВЕЛИКОГО И МОГУЧЕГО РУССКОГО ЯЗЫКА, и не забывая, что краткость — сестра таланта.
    3. Не забывайте использовать теги [сode=vba] …текст программы… [/code] для выделения текста программы подсветкой!
    4. Темы с просьбой выполнить какую-либо работу полностью за автора здесь не обсуждаются и переносятся в раздел ПОМОЩЬ СТУДЕНТАМ.

    >
    Подскажите как в диалоге при сохранении файла указать папку и тип файла
    , Подскажите как в диалоге при сохранении файла Ворд как указать папку и тип файла

    • Подписаться на тему
    • Сообщить другу
    • Скачать/распечатать тему



    Сообщ.
    #1

    ,
    05.09.10, 08:58

      Member

      **

      Рейтинг (т): нет

      ExpandedWrap disabled

        ‘диалог при сохранении файла

        With Dialogs(wdDialogFileSaveAs)

               .Name = «» ‘ имя файла

               .Show ‘показать

               ???’папка

               ???’тип файла

         End With


      coder



      Сообщ.
      #2

      ,
      05.09.10, 09:33

        Цитата Ципихович Эндрю @ 05.09.10, 08:58

        ExpandedWrap disabled

                .Name = «» ‘ имя файла

        Для папки просто так:

        ExpandedWrap disabled

                .Name = «C:» ‘ имя файла

        Добавлено 05.09.10, 09:39
        Для типа файла:

        ExpandedWrap disabled

                .Format = 1 ‘ 2, 3, 4, …

        Сообщение отредактировано: coder — 05.09.10, 09:39


        Ципихович Эндрю



        Сообщ.
        #3

        ,
        05.09.10, 10:33

          Member

          **

          Рейтинг (т): нет

          Спасибо!!!!!!

          ExpandedWrap disabled

            ‘диалог при сохранении файла

            With Dialogs(wdDialogFileSaveAs)

            ‘тип сохраняемого файла

            ‘0 — Документ Word

            ‘1 — Шаблон документа

            ‘2 — Обычный текст

            ‘3 — Обычный текст

            ‘4 — Обычный текст

            ‘5 — Обычный текст

            ‘6 — Текст в формате RTF

            ‘7 — Обычный текст

            ‘8 — Вэб-страница

            ‘9 — Вэб-страница в одном файле

            ’10 — Вэб-страница с фильтром

            ’11 — XML-документ

            ’12 — Word 97-2003 & 6.0/95 — RTF

            ’13 — Word 97-2003 & 6.0/95 — RTF

            ’14 — Works 6.0 & 7.0

                   .Format = 0 ‘0 — Документ Word, можно заремарчить или удалить данную строку, что означает .Format = 0

                   .Name = «» ‘имя сохраняемого файла «»

                   .Name = «C:» ‘место сораняемого файла, имя сохраняемого файла «»

                   .Name = «C:Имя» ‘место сораняемого файла, имя сохраняемого файла «Имя»

                   .Show ‘показать диалог сохранения файла, указываем эту строчку последней

            End With

          0 пользователей читают эту тему (0 гостей и 0 скрытых пользователей)

          0 пользователей:

          • Предыдущая тема
          • VB for Application
          • Следующая тема

          Рейтинг@Mail.ru

          [ Script execution time: 0,0244 ]   [ 16 queries used ]   [ Generated: 14.04.23, 17:32 GMT ]  

          Понравилась статья? Поделить с друзьями:
        • Vba word rows count
        • Vba word диалог выбора файла
        • Vba word replace wdreplaceall
        • Vba word двусторонняя печать
        • Vba word replace all text