excel - 在另存为对话框中选择目录
问题描述
如何添加Save As
对话框代码以便用户可以选择目录?
用户应该能够选择文件夹C
或者F
并且不应该能够更改文件名test
Sub Saved()
Application.DisplayAlerts = False
Worksheets("test").Copy
'there is now a new active workbook
With ActiveWorkbook
'save it
.SaveAs Filename:="test", FileFormat:=xlWorkbookDefault, Password:=1234, writerespassword:=12345
'optionally close it
.Close savechanges:=False
End With
End Sub
解决方案
其实很简单。
尝试这个
Sub Saved()
Dim Ret As Variant
Dim NewFileName As String
'~~> Let user select folder
Ret = BrowseForFolder
'~~> Check if user selected a folder
If Ret = False Then
MsgBox "Please select a folder"
Exit Sub
End If
If Right(Ret, 1) <> "\" Then Ret = Ret & "\"
'~~> Predecide the file name so user cannot change
NewFileName = Ret & "Text.xlsx"
'MsgBox NewFileName
Application.DisplayAlerts = False
Worksheets("test").Copy
'there is now a new active workbook
With ActiveWorkbook
'save it
.SaveAs FileName:=NewFileName, FileFormat:=xlWorkbookDefault, _
Password:=1234, writerespassword:=12345
'optionally close it
.Close savechanges:=False
End With
End Sub
'~~> Function to choose the folder
Function BrowseForFolder(Optional OpenAt As Variant) As Variant
Dim ShellApp As Object
Set ShellApp = CreateObject("Shell.Application"). _
BrowseForFolder(0, "Please choose a folder", 0, OpenAt)
On Error Resume Next
BrowseForFolder = ShellApp.self.Path
On Error GoTo 0
Set ShellApp = Nothing
Select Case Mid(BrowseForFolder, 2, 1)
Case Is = ":"
If Left(BrowseForFolder, 1) = ":" Then GoTo Invalid
Case Is = "\"
If Not Left(BrowseForFolder, 1) = "\" Then GoTo Invalid
Case Else
GoTo Invalid
End Select
Exit Function
Invalid:
BrowseForFolder = False
End Function
推荐阅读
- git - 如果我在分支“Foo2”并执行“git push origin Foo”,会发生什么?
- r - 为什么“传单”地图中的点对“滑块输入”没有反应?
- wordpress - WP Rest API 中的 401 错误(基本身份验证和 OAuth)
- java - How do I search my ArrayList for a specific persons details? How would i then edit or remove them?
- c# - 我为 Visual Studio 2015 安装了 Crystal Reports,但找不到
- python - 如何使用 Python 在 Maya 2017 中将选定对象添加到 renderLayerSetup?
- amazon-web-services - 通过 route53 模块创建别名 AWS CNAME 域时使用通配符
- python - Python - 调度程序阻止中断
- javascript - 如何使用一个 url 但每个 4 个不同的参数获取 API (POST)
- php - 离子发送 http.post 和 php 接收 GET 请求