我该如何纠正将结果返回到同一单元格中的函数,然后将其作为值特别粘贴到编写该函数的同一单元格上?
例如单元格B2,我编写了函数= txtGetId(A2) 所以现在B2返回了例如“ T1011”,现在我希望将结果粘贴为B2中的特殊值:)
这是我的功能,基本上遍历所有原始数据并自动分配新的ID。
Function txtGetID(CellRef As String) As String
Dim sh As Worksheet
Dim rw As Range
Dim numID As String
Dim RowCount As Integer
Dim txtID As String
Dim txtcellID As String
Dim ResID As String
Dim fflag As Integer
Dim FResID As String
Dim txtCellValue As String
RowCount = 0
Set sh = ActiveSheet
ResID = sh.Cells(ActiveCell.Row, 2).Value
fflag = 1
numID = "00"
Do While fflag = 1
fflag = 0
numID = Right("00" & LTrim(Str((Val(numID) + 1))), 2)
For Each rw In sh.Rows
If sh.Cells(rw.Row, 1).Value = "" Then
Exit For
End If
txtCellValue = sh.Cells(rw.Row, 1).Value
If ResID & numID = txtCellValue Then
fflag = 1
Exit For
End If
'txtcellID = sh.Cells(rw.Row, 1).Value
If sh.Cells(rw.Row, 1).Value = "" Then
Exit For
End If
Next rw
For Each rw In sh.Rows
If fflag = 1 Then
Exit For
End If
txtCellValue = sh.Cells(rw.Row, 5).Value
If ResID & numID = txtCellValue Then
fflag = 1
Exit For
End If
'txtcellID = sh.Cells(rw.Row, 3).Value
If sh.Cells(rw.Row, 5).Value = "" Then
Exit For
End If
Next rw
Loop
FResID = ResID & numID
txtGetID = FResID
End Function
在“ End of Function”语句之前写任何东西将是无用的,因为该函数将以最后的结果返回。我试图用这个
ActiveCell.Activate
ActiveCell.Select
activecell.Value=FResID
但是它什么也没做。
答案 0 :(得分:0)
您可以尝试的方法(简化):
1)创建您的函数,例如:
Public ADRS As String
Option Explicit
Function Test(RNG As Range) As String
ADRS = ActiveCell.Address
Test = RNG.Value
End Function
2)输入后,该函数将触发工作表计算事件,因此在特定的工作表下写入,例如:
Private Sub Worksheet_Calculate()
Range(ADRS).Value = Range(ADRS).Value
End Sub
您也可以将其放在ThisWorkbook
下,如下所示:
Private Sub Workbook_SheetCalculate(ByVal Sh As Object)
Range(ADRS).Value = Range(ADRS).Value
End Sub