简体   繁体   中英

Excel VBA: Copying Formula to any active cell

I am new to VBA coding and hope I can get some assistance here. I am trying to create code that would do the following for ANY cell (without specifying hard coded cell ranges or references):

  • input a formula in the active cell
  • copy it (fill) down 10 rows

In an attempt to insert the formula into the ActiveCell I tried:

Sub Test()
ActiveCell.formula = "=IF(ISBLANK(C5)*ISBLANK(D5),"",IF(ISBLANK(D5),(C5),CONCATENATE(C5,"" ["", D5, ""]"")))"
End Sub

However, this produces the 1004: Application-define or object-defined error

I've tried declaring Range objects for ActiveCell but still run into errors.

Any help on this would be highly appreciated.

ActiveCell.formula = "=IF(ISBLANK(C5)*ISBLANK(D5),"""",IF(ISBLANK(D5),(C5),CONCATENATE(C5,"" ["", D5, ""]"")))" 

您错过了将第一组嵌入式报价加倍的机会。

You can use following routine to copy formula from cell to VBE compatible format. See if it helps you:

 Public Sub CopyExcelFormulaInVBAFormat()
 Dim strFormula As String
 Dim objDataObj As Object

 '\Check that single cell is selected!
 If Selection.Cells.Count > 1 Then
     MsgBox "Select single cell only!", vbCritical
     Exit Sub
 End If

 'Check if we are not on a blank cell!
 If Len(ActiveCell.Formula) = 0 Then
     MsgBox "No Formula To Copy!", vbCritical
     Exit Sub
 End If

 'Add quotes as required in VBE
 strFormula = Chr(34) & Replace(ActiveCell.Formula, Chr(34), Chr(34) & Chr(34)) & Chr(34)

 'This is ClsID of MSFORMS Data Object
 Set objDataObj = CreateObject("New:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}")
 objDataObj.SetText strFormula, 1
 objDataObj.PutInClipboard
 MsgBox "VBA Format formula copied to Clipboard!", vbInformation

 Set objDataObj = Nothing

 End Sub

After inserting this routine. You just need to enter the formula normally in the cell. Then stay on the cell and run this code and it will copy to clipboard. Go to VBE and do CTRL+V to paste the code where required.

Originally posted on:

https://chandoo.org/forum/threads/copy-formula-from-excel-to-clipboard-in-vba-compatible-format.35997/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM