簡體   English   中英

如何僅從一個Excel工作表復制公式,該工作表可以使用宏動態增長到另一工作表

[英]How to copy only formulas from one excel sheet which can dynamically grow to another sheet using macro

我有兩個Excel工作表sheet1和sheet2。Sheet1是動態的Excel工作表,可能有添加列的機會。我已經編碼了將列標題從sheet1動態復制到sheet2的功能。

Sheet1:
Prdct Id   PrdctQty Unitprice PrdctQty 

  1         5           10       50
  2         10          10       100



sheet2:
Prdct Id   PrdctNme Unitprice PrdctQty 

當我打開工作表2時,這些標題會自動從工作表1中顯示(使用宏)。工作表2中有2個按鈕。

1.Display-display product details on matching Prdct Id  entered by the user(that also done through macro)
2.Add- To add new product,user can enter Prdct Id , PrdctNme, Unitprice and it will be copied to sheet1 (through macro)     

Sheet1還包含其他具有fromulas的列(在示例中未顯示),sheet1可以動態增長。 所以我想要的是當用戶輸入Prdct Id , PrdctNme, Unitprice PrdctQty應該自動出現在sheet2中(以及我暫時不包括的其他計算列),之后我可以將新產品添加到sheet1中

我嘗試了這段代碼(來自stackoverflow)

Sub dural()
Dim r As Range, ady As String
For Each r In Sheets("Sheet1").Cells.SpecialCells(xlCellTypeFormulas)
    ady = r.Address
    r.Copy Sheets("Sheet2").Range(ady)
Next

結束子

但是我得到的是sheet2中sheet1的完整副本以及values。我需要的只是公式而不是值

嘗試這樣的事情:

  Sub moveformulas ()

    Sheets(1).UsedRange.SpecialCells(xlCellTypeFormulas).Copy 
    Sheets(2).Range("A1").PasteSpecial

  End Sub 

即使我不確定正確的方法,我也找到了方法。

Sub dural()
Dim r As Range, ady,ady2 As String
For Each r In Sheets("Sheet1").Cells.SpecialCells(xlCellTypeFormulas)
    ady = r.Address
    ady2=r.formula
    Sheets("Sheet2").Range(ady).formula=ady2
Next

它對我有用

Sub CopyOnlyFormulas()

Sheets(1).UsedRange.Copy
Sheets(2).Cells.PasteSpecial Paste:=xlPasteFormulas, Operation:=xlNone

    For Each cell In Sheets(2).UsedRange
        If Not cell.HasFormula Then
            cell.Clear
        End If
    Next

End Sub


Sub CopyDataAndFormulas()
Sheets(1).UsedRange.Copy
Sheets(2).Cells.PasteSpecial Paste:=xlPasteFormulas, Operation:=xlNone
End Sub

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM