所以我創建了一個將單元格值與 100 (10^2) 相乘的宏。如果單元格只是一個值,它只是將單元格值乘以 100,但是如果它是一個公式,它會將公式放在括號中并在開頭添加 100* 因為您無法輕松撤消宏但我需要它,我試圖創建一個“撤消”宏。單元格值撤消非常容易,但是對于公式,我很難洗掉外括號。一個示例程序是: 原始:=1 1 變為 =100*(1 1) 并且撤消應該回傳到 =1 1(不帶括號)。
這是我的乘法代碼:
Private Sub MultiplySelectionBy100(Control As IRibbonControl)
Dim Cell As Range
For Each Cell In Selection
If Len(Cell.Value) > 0 And Application.IsNumber(Cell.Value) Then
If Cell.HasFormula Then
Cell.Formula = Replace(Cell.Formula, "=", "=100*(") & ")"
Else
Cell.Value = 100 * Cell.Value
End If
End If
Next
Application.OnUndo "Undo something", "UnDoSomething"
End Sub
對于 UNDO,這是我目前所擁有的:
Public Sub UnDoSomething()
Dim Cell As Range
Dim bet As String
For Each Cell In Selection
If Len(Cell.Value) > 0 And Application.IsNumber(Cell.Value) Then
If Cell.HasFormula Then
Cell.Formula = Replace(Cell.Formula, "=100*(", "=") 'This is not running
Cell.Formula = Replace(Cell.Formula, Chr(41), Chr(0))
Else
Cell.Value = 100 / Cell.Value
End If
End If
Next
End Sub
我不知道如何附加多個替換功能,但每次都會給我一個錯誤(主要是因為我洗掉了一個左括號但右括號仍然存在)。我也不能洗掉所有括號,因為公式中可能有更多括號。
也許你有一個想法...
uj5u.com熱心網友回復:
您的主要問題是第一個替換命令會將公式設定為無效,因為關閉的“)”仍然存在,并且 Excel(不是 VBA)不允許無效的公式,因此您會收到運行時錯誤(1004)。
您應該使用中間變數來處理公式的字串操作,并且只有在完全完成后,才將公式分配回單元格。如果您在 VBA 中處理公式,則使用中間變數總是一個好主意 - 您可以在將公式寫回單元格之前檢查公式是否真的符合預期。
您需要小心您的第二個替換陳述句:這將洗掉所有右括號字符,即使它與您的“撤消”無關。你應該(a)檢查你是否真的想洗掉它,(b)只洗掉最后一個右括號。
Dim f As String
f = cell.Formula
If Left(f, 6) = "=100*(" Then
f = Replace(cell.Formula, "=100*(", "=")
f = Left(f, Len(f) - 1)
cell.Formula = f
End If
或者,也許更容易
If Left(f, 6) = "=100*(" Then
f = "=" & Mid(f, 7, Len(f) - 7)
cell.Formula = f
End If
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/529609.html
標籤:擅长vba
