检查目标目录是否存在,如果不存在则进行创建,然后再进行

亚历克斯

我在其中一个工作表上有一个按钮,可让用户继续执行其任务以将他/她的模板另存为单独的工作簿在文件夹中。

这是我的代码

Private Sub ContinueButton_Click()
    Application.ScreenUpdating = 0
    Sheets(cmbSheet.Value).Visible = True
    Application.Goto Sheets(cmbSheet.Value).[a22], True
    Application.ScreenUpdating = 1
    Unload Me
End Sub

现在,我需要检查该文件夹是否存在,以防万一该文件夹不存在,我的用户应该可以创建该文件夹。

下面是我创建此文件夹的代码,但是我不知道如何将这两个功能连接在一起,因为我对VBA还是很陌生

Sub CreateDirectory()
Dim sep As String
sep = Application.PathSeparator
'sets the workbook's path as the current directory
ChDir ThisWorkbook.Path
MsgBox "The current directory is:" & vbCrLf & CurDir
'makes new folder in current directory
MkDir CurDir & sep & Settings.Range("C45").Value
MsgBox "The archive directory named " & Settings.Range("C45").Value & " has been created. The path to your directory " & Settings.Range("C45").Value & " is below. " & vbCrLf & CurDir & sep & Settings.Range("C45").Value
End Sub
AKS

我将对您的代码进行一些模块化:

首先在这里获取目录路径

Function getDirectoryPath()
    getDirectoryPath = ThisWorkbook.Path & Application.PathSeparator & Settings.Range("C45").Value
End Function

您可以使用此功能创建目录

Sub createDirectory(directoryPath)
    MkDir directoryPath
End Sub

您可以使用Dir功能检查目录是否存在

Dir(directoryPath, vbDirectory) 'empty string means directoryPath doesn't exist

单击按钮的最终功能:

Private Sub ContinueButton_Click()
    Application.ScreenUpdating = 0
    Sheets(cmbSheet.Value).Visible = True
    directoryPath = getDirectoryPath
    'Creating the directory only if it doesn't exist
    If Dir(directoryPath, vbDirectory) = "" Then
         createDirectory directoryPath
    End If
    Application.Goto Sheets(cmbSheet.Value).[a22], True
    Application.ScreenUpdating = 1
    Unload Me
End Sub

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

Linux:复制并创建目标目录(如果不存在)

检查目录是否存在,如果不存在则创建

指定的目标目录不存在

Shell脚本检查dir目录是否存在然后更改路径,如果不存在则使用该名称创建dir并检查文件名不存在

如果目录不存在,如何创建创建目录的目标?

VBA检查目录是否存在,如果存在退出子,否则不存在,创建

Ansible模板-目标目录不存在错误

检查文件是否存在,如果不存在则创建它

PYTHON TKINTER如何检查按钮是否存在,如何删除按钮,如果不存在则进行操作?

当目标目录不存在时如何创建符号链接?

在关联数组中创建对象(如果不存在),然后对其进行引用

如何检查目录是否存在,如果在Rust中不存在,则创建一个新目录?

如果目录不存在,如何创建?

如果Ruby不存在,则创建目录

创建目录(如果不存在)

检查目录是否不存在

如何检查是否已完成某件事,如果已存在则不再进行

制作一个.sh脚本来检查SSH连接是否存在,如果不存在,则进行连接

如果不存在则进行更新吗?

仅在源目录中不存在的情况下删除目标目录中的文件

检查div是否存在-如果不存在-再次检查直到创建

“ assets:install”命令失败,并显示错误“目标目录“ web”不存在”,为什么?

复制模板时出现“目标目录不存在”错误

使用不存在的目标目录重命名命令

检查表是否存在,如果不存在,请在SQL Server 2008中创建表

AngularFire检查值是否存在,如果不存在,则创建它

检查列表中是否存在用户名,如果不存在则仅创建用户

检查 $tablename 在 SQL Server 2017 中是否存在,如果不存在则创建表 $tablename

PHP 和 MYSQLI 检查用户 ID 是否存在,如果不存在则创建它