2015-04-21 38 views
1

我希望創建一個宏來請求用戶的「前綴」和「後綴」以及一個範圍。前綴將放置在每個公式的前面,而後綴將放置在整個範圍內每個公式的末尾。例如,如果A1包含ABC且前綴爲=LEFT(,後綴爲,1),則A1中的公式應從ABC更改爲=LEFT(ABC,1),因此僅顯示A如何創建一個可以在範圍內的公式中添加前綴和後綴的宏?

爲此提供用戶界面的最佳方式是通過表單。讓我們把它叫做 「宏包裝」:

enter image description here

這是它應該是什麼樣子的行動:

enter image description here

這裏是cmdApplycmdCancel按鈕我的VBA代碼:

Private Sub cmdApply_Click() 
Dim DataValue As Range 

For Each DataValue In Range(redtSelectRange) 
    If Left(DataValue.Formula, 1) = "=" Then 
    DataValue.Formula = "=" & _ 
     Trim(txtBefore.Text) & _ 
     Right(DataValue.Formula, Len(DataValue.Formula) - 1) & _ 
     Trim(txtAfter.Text) 
    Else 
    DataValue.Formula = "=" & _ 
     Trim(txtBefore.Text) & _ 
     DataValue.Formula & _ 
     Trim(txtAfter.Text) 
    End If 
Next DataValue 

End Sub 

Private Sub cmdCancel_Click() 
Unload Me 
End Sub 

但是,當我編譯上述我收到「運行時錯誤」 1004':應用程序定義或對象定義的錯誤「。

enter image description here

我試圖縮短cmdApply條件到I mmediate If語句:

Private Sub cmdApply_Click() 
Dim DataValue As Range 

For Each DataValue In Range(redtSelectRange) 
    DataValue.Formula = "=" & _ 
    Trim(txtBefore.Text) & _ 
    IIf(Left(DataValue.Formula, 1) = "=", Right(DataValue.Formula, Len(DataValue.Formula) - 1), DataValue.Formula) & _ 
    Trim(txtAfter.Text) 
    End If 
Next DataValue 

End Sub 

乃至中間體窗口顯示範圍內的第一個條目的正確的(預期的)輸出:

?Trim(txtBefore.Text) & IIf(Left(DataValue.Formula, 1) = "=", Right(DataValue.Formula, Len(DataValue.Formula) - 1), DataValue.Formula) & trim(txtAfter.Text) 
=round(1.2,0) 

我應該更改我的代碼以正確添加/ i爲每個範圍的公式添加前綴/後綴?

+0

調試器停止了哪一行? – FreeMan

+0

@FreeMan:它停止在'For Each'中的'DataValue.Formula ='賦值(我提供的那些)。 – Werner

回答

2

基於您的代碼,並從圖像您的樣品,你.Formula分配將最終被:

==round(1.2,0) 

要解決這個問題:

Private Sub cmdApply_Click() 
Dim DataValue As Range 

For Each DataValue In Range(redtSelectRange) 
    If Left(txtBefore.Text, 1) = "=" Then 
    DataValue.Formula = Trim(txtBefore.Text) & _ 
     Right(DataValue.Formula, Len(DataValue.Formula) - 1) & _ 
     Trim(txtAfter.Text) 
    Else 
    DataValue.Formula = "=" & _ 
     Trim(txtBefore.Text) & _ 
     DataValue.Formula & _ 
     Trim(txtAfter.Text) 
    End If 
Next DataValue 

End Sub 
1

試試這個:

Private Sub cmdApply_Click() 
    Dim DataValue As Range 
    For Each DataValue In Range(redtSelectRange) 
    'Your code had an additional "=" leading into this string below but in your 
    'example, there was already a leading "=" in the txtBefore.Text. If you 
    'don't know if it will always have a leading "=" then add some code to  
    'make sure only 1 is included 
    If Left(DataValue.Formula, 1) = "=" Then 
     DataValue.Formula = Trim(txtBefore.Text) & _ 
     Right(DataValue.Formula, Len(DataValue.Formula) - 1) & _ 
     Trim(txtAfter.Text) 
    Else 
     DataValue.Formula = "=" & _ 
     Trim(txtBefore.Text) & _ 
     DataValue.Formula & _ 
     Trim(txtAfter.Text) 
    End If 
    Next 'DataValue isn't required here 
End Sub 
+0

我忙着掃描舊家庭照片 - 你打了45秒我! – FreeMan

相關問題