我有两张excel vba工作簿:' Formini1.xlsm'作为源文件; ' Tampil1.xlsm'作为目标文件。
主要功能是:我在目标文件中进行了高级过滤搜索。当我编写关键字并单击此工作簿按钮时,它会在源文件中搜索并在目标文件中显示相关数据。
以下是代码:
Private Sub CommandButton1_Click()
Dim RangeKriteria As Range, RangeCopyTo As Range, RangeTabel As Range
Set RangeTabel = Workbooks("formini1.xlsm").Sheets("Sheet3").[A1].CurrentRegion
Set RangeCopyTo = Workbooks("tampil1.xlsm").Sheets("Sheet2").[L1]
Set RangeKriteria = Workbooks("tampil1.xlsm").Sheets("Sheet2").[A1:I10]
With Workbooks("tampil1.xlsm").Sheets("Sheet2")
.Cells.Clear
.[A1:I1].Value = Workbooks("formini1.xlsm").Sheets("Sheet3").[A1:I1].Value
.[A2].Value = "*" & TextBox1.Value
.[B3].Value = "*" & TextBox1.Value
RangeTabel.AdvancedFilter Action:=xlFilterCopy, _
CriteriaRange:=RangeKriteria _
, CopyToRange:=RangeCopyTo, _
Unique:=False
End With
End Sub
问题是,在实际实现中,源文件(" formini1.xlsm")并不总是被打开。有什么想法解决这个问题吗?
答案 0 :(得分:0)
如果源文件已关闭,您需要打开它。添加以下内容:
Sub Macro3()
Dim book As Workbook
Dim filepath As String
filepath = "C:\your_path\formini1.xlsm"
'Open the workbook as read only to avoid access conflicts
Set book = Workbooks.Open(Filename:=filepath, ReadOnly:=True)
' Close the workbook after you have read the data
book.Close
End Sub
我测试过该文件已经打开,对我来说,它并没有失败。如果它已经失败,如果已经打开,则捕获错误并继续。