我可以分配一个包含工作簿名称作为参数的字符串值吗?

时间:2019-05-15 20:14:41

标签: excel vba

总而言之,工作簿的名称每周更改两次,而我没有想到自动进行优化的另一种方法,而是决定仅显示一个输入框,在其中输入当前工作簿的名称,然后将其分配给: >

Public fileName As String
fileName = InputBox("Type here the current workbook's name: ")  

Dim ext As String
ext = ".xlsb"

Set wk = Excel.Workbooks(fileName & ext)
  

错误9:下标超出范围

1 个答案:

答案 0 :(得分:0)

  

从技术上讲,这并不是您所要的,但是让用户选择其中的文件是一种更好的编程实践。   操作系统界面,而不是让他们键入文件名,   最终达到了相同的目标。

我创建了一个自定义函数,用于通过FileDialog对象选择文件。作为可选参数,您可以在format参数中强制使用特定的文件类型。

get_file([format], [fullpath])

' Returns a file name of a selected file via the .FileDialog object
' Arguments:
'    [format] : Optional argument, if left empty any file format can be selected, _
                otherwise enforce what [format] was put in to be selected
'    [fullpath] : Optional argument, if left empty will only return FileName.xxx, _
                  otherwise will return full path (eg. D:\MyDir\Book.xlsx")
' Returns: A <String> with the selected filename.

函数的外观如下:

Private Function get_file(Optional ByVal format As String = "nomatch", _
                          Optional ByVal fullpath As Boolean = False) As String

    Dim fs As FileDialog: Set fs = Application.FileDialog(msoFileDialogFilePicker)
    Dim goodmatch As Boolean: goodmatch = False

    Do Until goodmatch = True
        With fs
            If .Show <> -1 Then
                .Title = "Choose a Workbook to work with"
                .AllowMultiSelect = False
                .InitialFileName = Application.DefaultFilePath
            End If

            If format = "nomatch" Then
                goodmatch = True
            Else
                format = Replace(format, ".", "")
                If Mid(.SelectedItems(1), InStrRev(.SelectedItems(1), ".") + 1) <> format Then
                    MsgBox "Please select a " & format & " file format", vbCritical
                Else
                    goodmatch = True
                End If
            End If
        End With
    Loop

    If fullpath = True Then
       get_file = fs.SelectedItems(1)
    Else
       get_file = Mid(fs.SelectedItems(1), InStrRev(fs.SelectedItems(1), "\") + 1)
    End If

End Function

该函数的示例用户:

Private Sub test()
    Dim wb As Workbook: Set wb = Workbooks.Open(get_file(".xlsx", fullpath:= True))
    ' saves a workbook of only .xlsx type from what user selected into wb variable
    Debug.Print wb.Name
End Sub

使用强制执行的[fullpath] True打开具有正确链接(.xlsx的{​​{1}}的工作簿,并打印{{1 }}对象保存在[format]变量中

enter image description here