Excel宏如果文件存在

时间:2012-10-25 07:41:08

标签: excel vba excel-vba

所以就像主题标题所说,我正在寻找一些宏的帮助。 我需要它来完成我的工作,所以每次执行客户端备份时他都会向邮箱发送邮件,这些邮件会在文件夹中导出。 这是邮件格式:

  

Backup Rapport Success Clients name File Backup Set Taak 2012-10-23(20 30)

宏需要做一些事情:

  • 提取客户名称
  • 提取或备份已成功或失败或错过
  • 并在右侧单元格中写入成功或失败的消息

这甚至可能吗?

Public Function FileFolderExists(strFullPath As String) As Boolean
'Author       : Ken Puls (www.excelguru.ca)
'Macro Purpose: Check if a file or folder exists
    On Error GoTo EarlyExit
    If Not Dir(strFullPath, vbDirectory) = vbNullString Then FileFolderExists = True

EarlyExit:
    On Error GoTo 0
End Function

Public Sub TestFolderExistence()
'Author       : Ken Puls (www.excelguru.ca)
'Macro Purpose: Test if directory exists
    If FileFolderExists("c:\test") Then
        MsgBox "Folder exists!"
    Else
        MsgBox "Folder does not exist!"
    End If
End Sub

1 个答案:

答案 0 :(得分:0)

以下内容将字符串拆分为单词(但只有在ClientName为一个单词时才会起作用。)

Sub Test()
    Const sIn As String = "Backup Rapport Geslaagd ClientName File Backup Set Taak 2012-10-23 (20 30), "
    Dim sArr() As String

    sArr = Split(sIn, Space(1))

    Debug.Print "Success=" & sArr(2)
    Debug.Print "ClientName=" & sArr(3)
    Debug.Print "Date=" & sArr(8)
End Sub

有很多方法可以将文本输入到单元格中。一个例子:

Range("A1").Value = "Hello"

Range("A2").Value = sArr(2)

修改

扩展sub以获取字符串和范围并输入文本:

Option Explicit

Sub SplitMailStringAndEnterValues(psMail As String, poRange As Range)
    Dim sArr() As String

    '***** Check that poRange is an object
    If Not poRange Is Nothing Then
        sArr = Split(psMail, Space(1))

        '***** Check that sArr is an array
        '***** and that it contains at least 9 strings
        If IsArray(sArr) And UBound(sArr) >= 8 Then
            '***** Enter values starting in range poRange and use
            '***** offset to place other values to the right
            poRange.Value = sArr(2)                 'Success
            poRange.Offset(0, 1).Value = sArr(3)    'ClientName
            poRange.Offset(0, 2).Value = sArr(8)    'Date
        End If
    End If
End Sub

现在为每个邮件字符串调用此函数,而不是在列中写入整个字符串:

Call SplitMailStringAndEnterValues("Backup Rapport Geslaagd ClientName File Backup Set Taak 2012-10-23 (20 30)", Range("Sheet2!A2"))