我正在尝试完成一个脚本,允许用户在双击单元格时选择另一个excel文件,然后使用该Excel文件将公式放入主excel文件中。
我无法单独使用单元格值,因为需要在脚本完成时查看公式栏中的文件路径。所以问题是输入的公式与它应该从中拉出的字符串文本不匹配。
为了澄清,我使用的名为FormulaPath的字符串最终是一个结尾为“...\00975-006-00[00975-006-00.xls]QuoteDetails'!
”的公式,这将是正确的公式。
但是当我使用它将公式输入范围时:
Range("A1").Formula = "=" & FormulaPath & "$C$100"
实际公式最终输入为"...[00975-006-00[00975-006-00.xls]Quote Details]00975-006-00[00975-006-00.xls]Q'!$C$100
注意重复?
我现在正在使用手机,如果格式很古怪,请原谅我。完整的脚本如下。谢谢!
Option Explicit
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
Dim ImportWB, QuoteWB As Workbook
Dim AdInsWS, AdInsCostWS As Worksheet
Dim ImportPathName As Variant
Dim FormulaPath As String
Set QuoteWB = ThisWorkbook
Set AdInsWS = QuoteWB.Sheets("Ad-Ins")
Set AdInsCostWS = QuoteWB.Sheets("Ad-ins cost")
If Not Intersect(Target, Range("B:B")) Is Nothing Then
'set default directory
ChDrive "Y:"
ChDir "Y:\Engineering Management\Manufacturing Sheet Metal\Quotes"
'open workbook selection
ImportPathName = Application.GetOpenFilename(FileFilter:="Excel Files (*.xls*), *.xls*", Title:="Please select a file")
If ImportPathName = False Then 'if no workbook selected
MsgBox "No file selected."
ElseIf ImportPathName = ThisWorkbook.Path & "\" & ThisWorkbook.Name Then 'if quote builder workbook selected
MsgBox "Current quote workbook selected, cannot open."
Else
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Workbooks.Open Filename:=ImportPathName, UpdateLinks:=False
Set ImportWB = ActiveWorkbook
FormulaPath = "'" & ImportWB.Path & "[" & ImportWB.Name & "]Quote Details'!"
AdInsCostWS.Range("B3").Formula = "=" & FormulaPath & "$C$100"
ImportWB.Close
End If
Cancel = True
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End If
End Sub
答案 0 :(得分:2)
我只需在FormulaPath字符串中添加反斜杠即可使您的脚本正常工作:
FormulaPath = "'" & ImportWB.Path & "\[" & ImportWB.Name & "]Quote Details'!"
答案 1 :(得分:0)
ImportWB.Path正在导入带有excel名称的Path,拆分路径字符串