参考input框方法的公式

我想通过Excel VBA应用Text(E2,"MM/DD/YYYY")公式。 我使用多个工作表,单元格目标和单元格引用不固定。 因此,我使用input框方法来完成正在工作的Cell目标,并且想通过input框方法手动select或更改公式中的单元格引用。 例如,如果我在A2单元格上面写公式,我的目标单元格是E2。 单元格select应通过input框进行。

最初我的计划是用inputboxselect两个东西,但我只是一个初学者,并没有设法做到这一点,因此改变了计划,并重新编写了代码。 但代码似乎有一些问题,而在input框编辑公式范围,有时它不考虑我的IPUT。 如果我说文本(E2,"MM/DD/YYYY")那么它select文本(D2或什么,“MM / DD / YYYY”)

 Option Explicit Sub FinalTxtDte() Dim Rng As range Dim LastRow As Long Dim Frmla As String Dim DestRng As range On Error Resume Next ' if the user presses "Cancel" Set Rng = Application.InputBox("Select a Cell which needs to be converted in Date format.", "Range Selection", Type:=8) Err.Clear On Error GoTo 0 If Not Rng Is Nothing Then Frmla = "=TEXT(" & Rng.Address("False", "False") & ",""MM/DD/YYYY"")" On Error Resume Next ' if the user presses "Cancel" Set DestRng = Application.InputBox("Select a Cell where you would like to get a Converted Date.", "Range Selection", Type:=8) Err.Clear On Error GoTo 0 If Not DestRng Is Nothing Then DestRng.Formula = Frmla LastRow = Rng.End(xlDown).Row DestRng.Select range(Selection, Selection.Offset(LastRow - Rng.Row, 0)).Select Selection.FillDown range(Selection, Selection.Offset(LastRow - Rng.Row, 0)).Value _ = range(Selection, Selection.Offset(LastRow - Rng.Row, 0)).Value End If End If End Sub 

下面的代码可以让你使用2 InputBox es来select单元格和公式目标(目前根据你的post-requaet是1单元格)。

我修改了第二个InputBox来select公式的目标范围。

如果用户在InputBox中select"Cancel"选项,则需要保持On Error Resume Next (以及后面的On Error GoTo 0 )。

 Option Explicit Sub TextDateFormula() Dim Rng As Range Dim LastRow As Long Dim Frmla As String, Txt As String Dim DestRng As Range On Error Resume Next ' if the user presses "Cancel" Set Rng = Application.InputBox("Select a cell.", "Range Selection", Type:=8) Err.Clear On Error GoTo 0 If Not Rng Is Nothing Then Frmla = "=TEXT(" & Rng.Address(True, True) & ",""MM/DD/YYYY"")" On Error Resume Next ' if the user presses "Cancel" Set DestRng = Application.InputBox("Select a range to add Decimal Hours.", "Range Selection", Type:=8) Err.Clear On Error GoTo 0 If Not DestRng Is Nothing Then DestRng.Formula = Frmla End If End If End Sub 

编辑1 :为了使公式不占绝对地址,修改下面的代码行:

 Frmla = "=TEXT(" & rng.Address(False, False) & ",""MM/DD/YYYY"")" 

您需要修改Address("Row Absolute", "Column Absolute")括号内的部分,请根据需要修改列和行设置。