您的代码做了很多选择,而对这些选择没有任何作用。在最好的情况下,最好是avoid using select,因为它会减慢您的代码速度(并且在大多数情况下是不必要的)。
此代码假定工作表为Sheet1,如果不更改工作表引用以适合您自己的工作表。
我为我想使用的所有数字和范围创建变量,这使代码更易于阅读和遵循(因为可以描述性地命名变量)。
我在第 1 行找到最后一列(假设这是标题行),这意味着如果添加或删除列,代码将完全一样。
找到列标题后,我们将贷方或借方列号分配给DebtCreditColumn,并使用它来定义我们的HeaderRange。
然后我们对AMNTColumn 执行相同的操作。
我添加了几个If...Then 语句来显示MsgBox,如果其中一个值为0(这意味着找不到标头),则中止代码。
然后从DebtCreditColumn 中减去AMNTColumn 以获得差值并分配给FormulaReferenceColumn。
然后在Debit or Credit 中找到LastRow 并将我们的TargetRange 设置为从第2 行到LastRow 的“AMNT 列”(LastRow 没有在您的代码中定义,所以我认为它是'借方或贷方”列)。
最后将FormulaReferenceColumn 合并到我们的公式中以写入我们的TargetRange。
像这样:
Sub ParanTest()
Dim DebtCreditColumn As Long
Dim AMNTColumn As Long
Dim LastColumn As Long
Dim FormulaReferenceColumn As Long
Dim LastRow As Long
Dim HeaderRange As Range
Dim TargetCell As Range
Dim TargetRange As Range
With Sheet1
LastColumn = .Cells(1, Columns.Count).End(xlToLeft).Column
Set HeaderRange = .Range(.Cells(1, 1), .Cells(1, LastColumn))
End With
For Each TargetCell In HeaderRange
If TargetCell.Value Like "Debit or Credit" Then
DebtCreditColumn = TargetCell.Column
Exit For
Else
'Go To Next Cell
End If
Next TargetCell
For Each TargetCell In HeaderRange
If TargetCell.Value Like "AMNT" Then
AMNTColumn = TargetCell.Column
Exit For
Else
'Go To Next Cell
End If
Next TargetCell
'In case the column can't be found, this will notify you and abort the code to avoid errors.
If DebtCreditColumn = 0 Then
MsgBox "A column header 'Debit or Credit' could not be found.", vbOKOnly, "No column found!"
Exit Sub
End If
'In case the column can't be found, this will notify you and abort the code to avoid errors.
If AMNTColumn = 0 Then
MsgBox "A column header 'AMNT' could not be found.", vbOKOnly, "No column found!"
Exit Sub
End If
FormulaReferenceColumn = DebtCreditColumn - AMNTColumn
With Sheet1
LastRow = .Cells(Rows.Count, DebtCreditColumn).End(xlUp).Row 'You can define whatever column works best for you
Set TargetRange = .Range(.Cells(2, AMNTColumn), .Cells(LastRow, AMNTColumn))
End With
TargetRange.FormulaR1C1 = "=IF(RC[" & FormulaReferenceColumn & "]=""Debit"",RC[-1],IF(RC[" & FormulaReferenceColumn & "]=""Credit"",-RC[-1]))"
End Sub