我使用FilePicker将工作簿定义为变量。在顶部,我将变量定义为public和string。我试图将其声明为工作簿,但它不起作用。当我尝试在另一个模块中进入此工作簿时,将其定义为字符串, 以下编译错误:
无效的限定词。
任何建议有什么问题吗?
Public wipreport As String
sub wip()
With Application.FileDialog(msoFileDialogFilePicker)
'Makes sure the user can select only one file
.AllowMultiSelect = False
.Title = "Select WIP Report"
.ButtonName = "OK"
'Filter to just the following types of files to narrow down selection options
.Filters.Add "Excel Files", "*.xlsx; *.xlsm; *.xls; *.xlsb", 1
'Show the dialog box
.Show
'Store in fullpath variable
wipreport = .SelectedItems.Item(1)
End With
end sub
另一个模块中的代码行,在此我收到此编译错误:
wipreport.Worksheets("1. WIP report").Select
谢谢您的帮助。
答案 0 :(得分:2)
编译错误是您可能遇到的最佳错误-编译器明确告知它不起作用。在这种情况下,wipreport.Worksheets("1. WIP report").Select
无法工作,因为wipreport
的类型为String
,并且它没有Worksheets
属性。
可能尝试这样的操作,如果wipreport
是打开的Excel文件的名称,它将起作用:
Workbooks(wipreport).Worksheets("1. WIP report").Select
如果wipreport
是文件的路径,则打开它是一个更好的选择:
Workbooks.Open wipreport
甚至为它设置一个变量:
Dim wb As Workbook
Set wb = Workbooks.Open(Filename:=wipreport)
在讨论主题时,有一个原因是,该问题在StackOverflow的#VBA中的投票数最高-How to avoid using Select in Excel VBA。
答案 1 :(得分:2)
FileDialog
将文件名作为String
对象返回,但是您正在尝试将其用作Workbook
。
如果用户选择了文件,则首先需要打开它,然后尝试选择工作表:
Set wb = Workbooks.Open(wipreport) 'open the file
wb.Worksheets("1. WIP report").Select ' your code