2016-09-21 36 views
-3

我在VBA中颇为新颖,并且编写了一个子程序,可以将单元格从一个文档复制粘贴到另一个文档中。更确切地说,我在文档1中工作,其中有几个产品的名称(全部在列“A”中)。对于这些产品,我需要在第二个文档中查找某些变量(例如销售额)。Excel变换功能

该子程序做的工作很好,但我想用它作为功能,即我想通过在单元格中输入“= functionname(productname)”来调用子程序。

我很感激任何有用的评论! 最佳,安德烈亚斯

Sub copy_paste_data() 

Dim strVerweis As String    
Dim Spalte      
Dim Zeile      
Dim findezelle1 As Range   
Dim findezelle2 As Range   
Dim Variable      
Dim Produkt      

'Variable I need to copy from dokument 2 
Variable = "frequency" 



'Produkt I need to copy data from document 2 
Produkt = Cells(ActiveCell.Row, 1) 



'path, file and shhet of document 2 
Const strPfad = "C:\Users\Desktop\test\"   
Const strDatei = "Bezugsdok.xlsx"   
Const strBlatt = "post_test"    

'open ducument 2 
Workbooks.Open strPfad & strDatei 
Worksheets(strBlatt).Select 

Set findezelle = ActiveSheet.Cells.Find(Variable) 
Spalte = Split(findezelle.Address, "$")(1) 

Set findezelle2 = ActiveSheet.Cells.Find(Produkt) 
Zeile = Split(findezelle2.Address, "$")(2) 



'copy cell that I need 
strZelle = Spalte & Zeile     'Zelladresse 
strVerweis = "'" & strPfad & "[" & strDatei & "]" & strBlatt & "'!" & strZelle 

'close document 2 
Workbooks(strDatei).Close savechanges:=False 



With ActiveCell 
    .Formula = "=IF(" & strVerweis & "="""",""""," & strVerweis & ")"  
    .Value = .Value              
End With 

End Sub 

回答

0

下面是一个例子,以创建带来的只是细胞的前3个字母的功能:

Public Function FirstThree(Cell As Range) As String 
    FirstThree = Left(Cell.Text, 3) 
End Function 

而在一个Excel工作表中使用,这将是这样的:

=FirstThree(b1) 
0

如果子工作正常,你只是想让它更容易打电话,你可以添加一个热键来执行宏。在开发人员选项卡上点击宏然后选项。然后你可以添加一个快捷键(Crtl +“你想要的键”它可以是已经用过的快捷键,如C,V,S,但是你将失去这些功能(复制,粘贴保存,打印) enter image description here

+0

谢谢!这是迄今为止我已经实现它的任何建议如何让它作为一个函数运行,仍然非常感谢! – AnBA