Excel VBA中单行中的多个OFFSET函数不起作用 - 为什么?

时间:2016-02-04 16:37:02

标签: excel vba excel-vba

简单地说,我正在尝试在Excel中使用看似相当简单的宏。它需要在Mac和PC上运行良好,但我需要遍历A列中的所有行,然后为格式的每一行创建一个文件夹:

我知道我可以做的更多(检查文件夹是否已经存在等),但目前我只想让mkdir线运行。有人能帮忙吗?谢谢。

列A的文本列B的文本 - 列C的文本

Sub CreateDirs()
    Dim R As Range
    Dim RootFolder As String
    RootFolder = ThisWorkbook.path
    For Each R In Range("A7:A64000")
        If Len(R.Text) > 0 Then
            On Error Resume Next
            MkDir RootFolder & Application.PathSeparator & R.Text & " " & R.Offset(0, 1).Text & " - " & R.Offset(0, 2).Text
            On Error GoTo 0
        End If
    Next R
End Sub

1 个答案:

答案 0 :(得分:1)

在此处测试时,您的代码在Windows下运行正常。 但是,由于您还需要在Mac上执行,因此您可能希望远离MkDir。您还想检查文件夹是否存在。

您的问题的完整答案可以在他的网站Ron de Bruin上找到:http://www.rondebruin.nl/mac/mac010.htm

他的代码发布在上面的链接上:

Sub MakeFolderTest1()
'Make folder on the Desktop
    MakeFolderIfNotExist (MacScript("return (path to desktop folder) as string") & "TestFolder1")
End Sub

Sub MakeFolderTest2()
'Add folder in the same path as your workbook with this code
    MakeFolderIfNotExist (ThisWorkbook.Path & Application.PathSeparator & "TestFolder2")
End Sub


'Change the path of the two macro below before you test them

Sub MakeFolderTest3()
'Enter the complete path
    MakeFolderIfNotExist ("YosemiteLacie256:Users:rondebruin:Desktop:TestFolder3")
End Sub

Sub MakeFolderTest4()
'Do not include the harddisk name if you use a posix path
    MakeFolderIfNotExist ("/Users/rondebruin/Desktop/TestFolder4")
End Sub


Function MakeFolderIfNotExist(Folderstring As String)
'Ron de Bruin, 22-June-2015
' http://www.rondebruin.nl/mac/mac010.htm
    Dim ScriptToMakeFolder As String
    Dim str As String
    If Val(Application.Version) < 15 Then
        ScriptToMakeFolder = "tell application " & Chr(34) & _
                             "Finder" & Chr(34) & Chr(13)
        ScriptToMakeFolder = ScriptToMakeFolder & _
                "do shell script ""mkdir -p "" & quoted form of posix path of (" & _
                        Chr(34) & Folderstring & Chr(34) & ")" & Chr(13)
        ScriptToMakeFolder = ScriptToMakeFolder & "end tell"
        On Error Resume Next
        MacScript (ScriptToMakeFolder)
        On Error GoTo 0

    Else
        str = MacScript("return POSIX path of (" & _
                        Chr(34) & Folderstring & Chr(34) & ")")
        MkDir str
    End If
End Function

他的网站是Excel VBA开发的绝佳资源。