我有两张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
但问题是,我必须将这些文件放在不同的文件夹中,所以我将RangeTabel更改为此代码:
Set RangeTabel = Workbooks("C://project/database/formini1.xlsm").Sheets("Sheet3").[A1].CurrentRegion
但它说错误。我不知道为什么。有没有想法,所以我可以在工作簿上创建子文件夹路径?
非常感谢
答案 0 :(得分:0)
如果工作簿已经打开,您只需按名称引用它们,例如
Workbooks("formini1.xlsm")
如果它们未打开,则需要先使用
打开它们Dim wb As Workbook
Set wb = Workbooks.Open("C://project/database/formini1.xlsm") ' though need to verify this if you are using a mac
然后参考
Set RangeTabel = wb.Sheets("Sheet3").[A1].CurrentRegion
如果您使用的是Windows,我希望路径看起来更像
"C:\TopFolder\NextFolder"
请点击此处获取有关Mac文件路径和获取文件的帮助:
https://www.rondebruin.nl/mac/mac015.htm
https://www.rondebruin.nl/mac/section3.htm
从here建议,对于Mac Excel 2016,需要Open
方法中的完全限定路径,例如
"/Users/User/Documents/FileName.xlsm"
以下是使用Windows和我提供的链接中的IsFileOpen函数的测试:
Sub Test
If Not IsFileOpen("C:\TopFolder\NextFolder\FileName.xlsx") Then
Set wb = Workbooks.Open("C:\TopFolder\NextFolder\FileName.xlsx")
End If
End Sub
Function IsFileOpen(filename As String)
Dim filenum As Integer, errnum As Integer
On Error Resume Next ' Turn error checking off.
filenum = FreeFile() ' Get a free file number.
' Attempt to open the file and lock it.
Open filename For Input Lock Read As #filenum
Close filenum ' Close the file.
errnum = Err ' Save the error number that occurred.
On Error GoTo 0 ' Turn error checking back on.
' Check to see which error occurred.
Select Case errnum
' No error occurred.
' File is NOT already open by another user.
Case 0
IsFileOpen = False
' Error number for "Permission Denied."
' File is already opened by another user.
Case 70
IsFileOpen = True
' Another error occurred.
Case Else
Error errnum
End Select
End Function
答案 1 :(得分:0)
您可以使用辅助函数来设置工作簿,并给出其路径广告名称(注释中的说明):
Function GetWorkbook(wbPath As String, wbName As String) As Workbook
On Error Resume Next
Set GetWorkbook = Workbooks(wbName) 'try getting wanted workbook between already opened ones
If GetWorkbook Is Nothing Then Set GetWorkbook = Workbooks.Open(wbPath & "\" & wbName) 'if unsuccesfully then open it
End Function
您可以在代码中使用,如下所示:
Set RangeTabel = GetWorkbook("C:\\project\database", "formini1.xlsm").Sheets("Sheet3").[A1].CurrentRegion
当然,您可以添加更多代码来处理其他可能的错误,例如: