Excel VB 打开文件 OSX 和 Windows

2024-04-04

我有一个电子表格,它使用一些基本代码来让用户选择一个文件(txt 文件)。它在 Windows 上完美运行,但在 OSX 上显然由于 FileDialog 调用的差异而失败。我已经做了一些研究,但似乎找不到太多有关在 OSX 和 Windows 上打开 Excel/VB 文件对话框的信息。

当前的代码是,

FileToOpen = Application.GetOpenFilename _
(Title:="Please choose a file to import", _
FileFilter:="Excel Files *.xls (*.xls),")
''
If FileToOpen = False Then
MsgBox "No file specified.", vbExclamation, "Duh!!!"
Exit Sub
Else
Workbooks.Open Filename:=FileToOpen
End If

答案可以在这里找到——http://msdn.microsoft.com/en-us/library/office/hh710200%28v=office.14%29.aspx http://msdn.microsoft.com/en-us/library/office/hh710200%28v=office.14%29.aspx

代码如下,

OSX

Sub Select_File_Or_Files_Mac()
    Dim MyPath As String
    Dim MyScript As String
    Dim MyFiles As String
    Dim MySplit As Variant
    Dim N As Long
    Dim Fname As String
    Dim mybook As Workbook

    On Error Resume Next
    MyPath = MacScript("return (path to documents folder) as String")
    'Or use MyPath = "Macintosh HD:Users:Ron:Desktop:TestFolder:"

    ' In the following statement, change true to false in the line "multiple 
    ' selections allowed true" if you do not want to be able to select more 
    ' than one file. Additionally, if you want to filter for multiple files, change 
    ' {""com.microsoft.Excel.xls""} to 
    ' {""com.microsoft.excel.xls"",""public.comma-separated-values-text""}
    ' if you want to filter on xls and csv files, for example.
    MyScript = _
    "set applescript's text item delimiters to "","" " & vbNewLine & _
               "set theFiles to (choose file of type " & _
             " {""com.microsoft.Excel.xls""} " & _
               "with prompt ""Please select a file or files"" default location alias """ & _
               MyPath & """ multiple selections allowed true) as string" & vbNewLine & _
               "set applescript's text item delimiters to """" " & vbNewLine & _
               "return theFiles"

    MyFiles = MacScript(MyScript)
    On Error GoTo 0

    If MyFiles <> "" Then
        With Application
            .ScreenUpdating = False
            .EnableEvents = False
        End With

        MySplit = Split(MyFiles, ",")
        For N = LBound(MySplit) To UBound(MySplit)

            ' Get the file name only and test to see if it is open.
            Fname = Right(MySplit(N), Len(MySplit(N)) - InStrRev(MySplit(N), Application.PathSeparator, , 1))
            If bIsBookOpen(Fname) = False Then

                Set mybook = Nothing
                On Error Resume Next
                Set mybook = Workbooks.Open(MySplit(N))
                On Error GoTo 0

                If Not mybook Is Nothing Then
                    MsgBox "You open this file : " & MySplit(N) & vbNewLine & _
                           "And after you press OK it will be closed" & vbNewLine & _
                           "without saving, replace this line with your own code."
                    mybook.Close SaveChanges:=False
                End If
            Else
                MsgBox "We skipped this file : " & MySplit(N) & " because it Is already open."
            End If
        Next N
        With Application
            .ScreenUpdating = True
            .EnableEvents = True
        End With
    End If
End Sub

Function bIsBookOpen(ByRef szBookName As String) As Boolean
' Contributed by Rob Bovey
    On Error Resume Next
    bIsBookOpen = Not (Application.Workbooks(szBookName) Is Nothing)
End Function

Windows

Sub Select_File_Or_Files_Windows()
    Dim SaveDriveDir As String
    Dim MyPath As String
    Dim Fname As Variant
    Dim N As Long
    Dim FnameInLoop As String
    Dim mybook As Workbook

    ' Save the current directory.
    SaveDriveDir = CurDir

    ' Set the path to the folder that you want to open.
    MyPath = Application.DefaultFilePath

    ' You can also use a fixed path.
    'MyPath = "C:\Users\Ron de Bruin\Test"

    ' Change drive/directory to MyPath.
    ChDrive MyPath
    ChDir MyPath

    ' Open GetOpenFilename with the file filters.
    Fname = Application.GetOpenFilename( _
            FileFilter:="Excel 97-2003 Files (*.xls), *.xls", _
            Title:="Select a file or files", _
            MultiSelect:=True)

    ' Perform some action with the files you selected.
    If IsArray(Fname) Then
        With Application
            .ScreenUpdating = False
            .EnableEvents = False
        End With

        For N = LBound(Fname) To UBound(Fname)

            ' Get only the file name and test to see if it is open.
            FnameInLoop = Right(Fname(N), Len(Fname(N)) - InStrRev(Fname(N), Application.PathSeparator, , 1))
            If bIsBookOpen(FnameInLoop) = False Then

                Set mybook = Nothing
                On Error Resume Next
                Set mybook = Workbooks.Open(Fname(N))
                On Error GoTo 0

                If Not mybook Is Nothing Then
                    MsgBox "You opened this file : " & Fname(N) & vbNewLine & _
                           "And after you press OK, it will be closed" & vbNewLine & _
                           "without saving. You can replace this line with your own code."
                    mybook.Close SaveChanges:=False
                End If
            Else
                MsgBox "We skipped this file : " & Fname(N) & " because it is already open."
            End If
        Next N
        With Application
            .ScreenUpdating = True
            .EnableEvents = True
        End With
    End If

    ' Change drive/directory back to SaveDriveDir.
    ChDrive SaveDriveDir
    ChDir SaveDriveDir
End Sub


Function bIsBookOpen(ByRef szBookName As String) As Boolean
' Contributed by Rob Bovey
    On Error Resume Next
    bIsBookOpen = Not (Application.Workbooks(szBookName) Is Nothing)
End Function

选取器功能

Sub WINorMAC()
' Test for the operating system.
    If Not Application.OperatingSystem Like "*Mac*" Then
        ' Is Windows.
        Call Select_File_Or_Files_Windows
    Else
        ' Is a Mac and will test if running Excel 2011 or higher.
        If Val(Application.Version) > 14 Then
            Call Select_File_Or_Files_Mac
        End If
    End If
End Sub
Sub WINorMAC_2()
' Test the conditional compiler constants.
    #If Win32 Or Win64 Then
        ' Is Windows.
        Call Select_File_Or_Files_Windows
    #Else
        ' Is a Mac and will test if running Excel 2011 or higher.
        If Val(Application.Version) > 14 Then
            Call Select_File_Or_Files_Mac
        End If
    #End If
End Sub
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Excel VB 打开文件 OSX 和 Windows 的相关文章

  • 在用户窗体终止/关闭 VBA 时调用数组

    我有一个问题 我想在用户窗体关闭时将用户窗体的内容存储在数组中 我认为我的语法正确 但似乎不会在用户窗体初始化时重新填充 我尝试将数组放入其自己的模块中 但这也不起作用 有人愿意启发我吗 示例代码 Public Sub DPArrayStu
  • macOS Pluginkit 输出中的前缀是什么意思?

    执行中pluginkit match在终端中产生以下输出 跳过不重要的行 com apple ncplugin weather 1 0 com apple share SinaWeibo post 1 0 H com apple Inter
  • 使用 Webkit 的调试版本运行 Safari

    我通过运行以下命令编译了 webkit 的调试版本 工具 脚本 build webkit debug 成功构建后 我尝试通过运行以下命令来使用已编译的 Webkit 调试版本来运行 safari sudo Tools Scripts run
  • 使用 python 中的公式函数使从 Excel 中提取的值的百分比相等

    import xlrd numpy excel Users Bob Desktop wb1 xlrd open workbook excel assignment3 xlsx sh1 wb1 sheet by index 0 colA co
  • Excel 公式从单元格中获取字符串值并按字母顺序对其字符进行排序

    你能帮我制作一个 Excel 公式 从单元格中获取字符串值并按字母顺序对其字符进行排序吗 Ex 原始单元格值 BACR 已排序的字符单元格 ABCR 编辑 2022 年 4 月 29 日 随着 Office 365 Excel 中引入的动态
  • 监控 Thunderbolt 端口连接的变化

    我正在满足一个要求 需要监视 Thunderbolt 端口连接的变化 当 Thunderbolt 电缆连接或断开时 我尝试使用IOServiceMatching kIOUSBInterfaceClassName from IOKit框架但我
  • 使用 Python Pandas 获取多个值来制作表格

    使用我的代码 我可以将两个 Excel 数据库连接到 1 中 问题是它只显示收入列 而不显示列展示次数 为了更清楚 我留下了代码和示例 我尝试过 df1 df1 pivot index Cliente columns Fecha value
  • 如何使用 C# 了解 Excel 中的分页符 [关闭]

    Closed 这个问题不符合堆栈溢出指南 help closed questions 目前不接受答案 我正在使用 C 创建并格式化 Excel 电子表格 因此我需要格式化 合并单元格 更改字体等 直到第一页的最后 如何知道 Excel 电子
  • NSView 鼠标跟踪

    我在 Mac OS X 上遇到了 Cocoa NSView 的奇怪行为 我在 NSView 容器中有一个自定义 NSView 这个自定义 NSView 跟踪鼠标移动 点击 并有一个工具提示 当我在所描述的视图上方添加 NSView 时 即使
  • OS X Cocoa 自动布局隐藏元素

    我正在尝试使用新的自动布局 http developer apple com library mac documentation UserExperience Conceptual AutolayoutPG Articles Introdu
  • 打开特定工作表上的 Excel 文件

    我有一个包含 5 个工作表的 Excel 文件 我想用 C 代码打开它 当它打开时 我希望激活第 3 页 我怎样才能做到这一点 像这样 using Excel Excel Application excelApp new Excel App
  • 从 Excel VBA 调用 Bloomberg BQL 查询

    出于复杂的原因 我想在 VBA 中自动调用 Bloomi BQL 查询 我正在从 VBA 脚本更改 Excel 工作表中 BQL Query 公式的输入 并调用 Application Calculate 来运行查询 显示更改为 N A 请
  • 绘制持续时间图表

    从我在写这篇文章之前所做的阅读中 我相当确定我需要创建甘特图 但我不知道这是否是正确的路线 需要将开始时间和结束时间的数据作为一个单位绘制在 Excel 图表上 Y 轴为日期 X 轴为一天中的小时 开始时间和结束时间的格式是 Excel 数
  • VBA复制单元格值和格式

    我如何修改以下代码以便不仅复制值而且复制字体样式 例如大胆或不大胆 谢谢 Private Sub CommandButton1 Click Dim i As Integer Dim a As Integer a 15 For i 11 To
  • 有 Mac 版的 IE 测试器吗? [关闭]

    就目前情况而言 这个问题不太适合我们的问答形式 我们希望答案得到事实 参考资料或专业知识的支持 但这个问题可能会引发辩论 争论 民意调查或扩展讨论 如果您觉得这个问题可以改进并可能重新开放 访问帮助中心 help reopen questi
  • 未找到符号,预计出现在平面命名空间 ObjC++ 中

    我可能遇到了一个简单的问题 但是在编译过程中没有任何信息错误或警告来提醒我出了什么问题 我有一个 Objective C 应用程序 其中包含 C 主文件和 ObjC 头文件 它构建得很好 但是当运行时 它会给出以下错误消息 Dyld Err
  • 为什么 MOVE CURSOR 在 OS X Mountain Lion 上不显示?

    我正在做一个项目 想看看 Swing 提供的每个光标是什么样子的 public class Test public static void main String args JFrame frame new JFrame frame set
  • 自动电子邮件生成无法解析多个收件人

    我有一个 VBA 脚本 可以创建并保存草稿电子邮件 为了添加收件人 它从链接的 Excel 表中提取一个字符串并将其添加到 Recipients 对象中 对于只有单一收件人的电子邮件 这就像一个魅力 用户所需要做的就是打开草稿 花 5 秒钟
  • Excel:COUNTIF 函数将“小于”字符视为运算符

    预读说明 我使用的是 LibreOffice 而不是 Excel 但大多数功能应该适用于两者 我正在制作一个电子表格 其中有大量数据 对于每个属性 例如员工数量或姓名 我需要一个函数来计算包含每个不同值的行数 我已经提取了不同的值 现在我使
  • 如何使用 VBA 将行从一张 Excel 工作表复制到另一张 Excel 工作表并创建重复项?

    我有一个包含两张表的 Excel 工作簿 sheet1 在 A 到 R 列中包含一个大型数据表 标题位于第 1 行 Sheet2 在 A 到 AO 列中包含数据 我试图使用 VBA 从sheet1 复制行并将它们粘贴到sheet2 的末尾

随机推荐