VBA运行时错误91与.xlsm文件但不是.xlsx

时间:2018-01-04 22:30:40

标签: excel vba runtime-error

我的程序按照预期的方式使用非宏excel文件,但无论出于何种原因,当我尝试将它与宏工作簿一起使用时,它会给出运行时错误91.变量看起来不像Fname时加载任何东西这是一本宏观书。我怀疑这可能是因为公司设置是为了让用户在使用时启用宏。此代码段似乎无法加载宏书的文件路径。

Fname = Application.GetOpenFilename( _
    FileFilter:="XLS Files (*.xls),*.xls,XLSM Files (*.xlsm),*.xlsm", _
    Title:="Select a workbook", _
    MultiSelect:=False)

SheetName = Application.InputBox("Please enter the name of the output tab", , , , , , , 2)

pulled = sh1.Range("B1:B30")
WSoutputs = sh1.Range("B1:B30")

sh4.Range("J1:J28").ClearContents
Set sh2 = Workbooks.Open(Fname)

有没有办法从宏书中读取数据而无需启用它?如果不是,我将如何提示用户像正常一样打开文件并点击启用宏?

完整代码:

Option Explicit

Sub Pull()
Dim sh1 As Worksheet
Dim sh2 As Workbook
Dim sh3 As Worksheet
Dim sh4 As Worksheet
Dim Path As String
Dim i As Integer
Dim arg As String
Dim pulled
Dim WSoutputs
Dim Comp(30, 0) As Variant
Dim Fname As Variant
Dim SheetName

Set sh1 = ThisWorkbook.Sheets("Refs")
Set sh3 = ThisWorkbook.Sheets("Output")
Set sh4 = ThisWorkbook.Sheets("Inputs")

On Error GoTo Err:

Fname = Application.GetOpenFilename( _
    FileFilter:="XLS Files (*.xls),*.xls,XLSM Files (*.xlsm),*.xlsm,XLSX Files (*.xlsx),*.xlsx", _
    Title:="Select a workbook", _
    MultiSelect:=False)

SheetName = Application.InputBox("Please enter the name of the output tab", , , , , , , 2)

pulled = sh1.Range("B1:B30")
WSoutputs = sh1.Range("B1:B30")

sh4.Range("J1:J28").ClearContents
Set sh2 = Workbooks.Open(Fname)



For i = (LBound(pulled) + 2) To UBound(pulled)
    pulled(i, 1) = Trim(pulled(i, 1))
    pulled(i, 1) = sh2.Sheets(SheetName).Range(pulled(i, 1))
    WSoutputs(i, 1) = sh3.Range(WSoutputs(i, 1))
    If pulled(i, 1) = WSoutputs(i, 1) Then
        Comp(i - 3, 0) = "Match"
    Else
        Comp(i - 3, 0) = pulled(i, 1)
    End If
Next i
sh2.Close

sh4.Range("J1:J28") = Comp

Exit Sub

Err:
MsgBox ("Make sure the Workbook and tab names are correct. Make sure the output format matches this workbook")
sh4.Range("J1:J28").ClearContents
If Fname <> "False.xlsx" Or Fname <> "False.xlsm" Then
    sh2.Close
End If
End Sub

循环似乎没有做我想要的东西,因为Sh2变为空。此外,pull和Wsoutput包含单元格引用(例如B3),输入和输出格式在工作表之间是相同的。

1 个答案:

答案 0 :(得分:0)

我想这个,但你应该发布尽可能多的代码。我不知道如何定义以下内容。无论如何要试试这个。

Set pulled = sh1.Range("B1:B30")
Set WSoutputs = sh1.Range("B1:B30")