通过VBA引用的工作簿不接受变量

时间:2019-05-08 12:14:19

标签: excel vba

我正在尝试建立对其他工作簿的引用,因此该位置是静态的:=ARRAYFORMULA(QUERY({ROW(A:A), B:B}, "select Col1 where Col2 =1 or Col2 =3", 0))

由于这些参考依据月份的不同而有所变化,因此,为了方便使用,我想设置一个输入框,在其中可以键入01或04这样的数字,并且它将交换参考中的月份部分。

到目前为止,我的代码如下:

G:\XY\XY\[Workbook2019.xlsx]2019-04'!C1

奇怪的是,我似乎得到了正确的参考,但是该单元由于某种原因不会接受该编号,并提示我从工作簿中选择一张纸。

我似乎找不到问题。 任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

我个人将对此进行充实,以避免用户输入中的其他错误。可以通过使用一个功能来测试用户输入的标准是否正确,然后循环播放直到输入正确或用户取消

Private Function TestUserInput(v As String) As Boolean
    TestUserInput = False

    If IsNumeric(v) And Len(v) <= 2 Then
        If CLng(v) > 0 And CLng(v) <= 12 Then
            TestUserInput = True
        End If
    End If
End Function

Public Sub MonthRef()
    Dim strMonth As String
    Dim IsUserInputValid As Boolean
    Dim InputBoxPrompt As String

    InputBoxPrompt = "Enter month as integer (e.g. 01 for Jan; 02 for Feb.)"

    Do
        strMonth = Trim(InputBox(InputBoxPrompt, "Month"))

        ' Test if strMonth is valid
        IsUserInputValid = TestUserInput(strMonth)

        ' Handle User cancelled
        If strMonth = vbNullString Then
            Exit Sub
        ' If input is not valid then prompt user
        ElseIf IsUserInputValid = False Then
            MsgBox prompt:="Input not valid. " & InputBoxPrompt, Title:="Error"
        End If
        ' Loop until input is valid or User cancels
    Loop Until IsUserInputValid

    Range("B4").Formula= "='G:\XY\[XY.xlsx]2019-" & Format(strMonth, "00") & "'!C1"
End Sub
相关问题