检查目标目录是否存在,如果不存在则进行创建,然后再进行 [英] Check is destination directory exist then proceed if not then create it and proceed afterwards

查看:167
本文介绍了检查目标目录是否存在,如果不存在则进行创建,然后再进行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a button on one of the worksheets that lets user to continue with his task to save his/her template as a separate workbook in the folder.

这是我的代码

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

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

Now what I need is to check if that folder exist, in case if the folder does not exist my user should be able to create it.

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

My code to create this folder is here below, but how to connect this 2 functions together I simply have no idea, since I am fairly new to 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

推荐答案

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

I am going to modularize your code a little bit:

首先在这里获取目录路径

First get the directory path here

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

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

You can create the directory using this function

Sub createDirectory(directoryPath)
    MkDir directoryPath
End Sub

您可以使用Dir函数检查目录是否存在

You can check if a directory exists or not using Dir function

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

这篇关于检查目标目录是否存在,如果不存在则进行创建,然后再进行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆