![](/img/trans.png)
[英]Changing value of a cell based on the value of two cells - VBA Excel
[英]Excel changing multiple cell details based on a specific cells value
Excel 公式和 vba 的超級新手。 感謝您提供的任何見解。
我正在嘗試在我的電子表格中實現語言切換器。 我目前有以下工作表:數據(在列中輸入值的位置)、摘要(在數據工作表中輸入的所有內容的摘要)、F(存儲函數和下拉列表項的位置)、T(英語/法語翻譯)
There are cells in all worksheets that will be translated when either English or French language is chosen. 在 T 工作表中有 3 列,其中 A 是參考列,B 有英文單詞,C 有翻譯的法語單詞。
切換語言的下拉菜單位於數據工作表中。 我在 Visual Basic 編輯器中輸入了以下代碼(雙擊列表中的數據工作表后)。
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Set Target = Range("C5")
Dim langCol
If Target.Value = "English" Then
langCol = 2 'now it's in english
Else
langCol = 3 'now it's in french
End If
Sheets("Data").Cells(1, 1).Value = Sheets("T").Cells(5, langCol).Value
Sheets("Data").Cells(2, 1).Value = Sheets("T").Cells(6, langCol).Value
'....many more cell swaps here 100 total
End Sub
此代碼在我將其作為“工作表選擇更改”運行時有效,並且當我從位於“C5”的下拉列表中選擇英語或法語時按預期翻譯所有內容。 我的問題是這段代碼只有在我點擊離開“C5”單元格后才會執行。 期望的結果是在選擇語言時進行翻譯,而“C5”單元仍處於活動狀態。
當我用以下代碼交換開頭的代碼行時:
Private Sub Worksheet_Change(ByVal Target As Range)
該代碼僅在“結束子”之前有單個單元格交換時才有效。 一旦添加了額外的單元交換,Excel (2007) 就會崩潰並重新啟動。
上面的代碼中是否缺少我顯然會導致錯誤的內容? 我沒有從程序本身得到任何反饋。
我認為進行 100 次細胞交換可能是問題所在。 有沒有更聰明的方法來處理通配符或更優雅的方法?
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
On Error GoTo ClearError ' mainly to prevent exiting without enabling events
' Target could be multiple cells. Restrict to one cell.
Dim tCell As Range: Set tCell = Intersect(Range("C5"), Target)
If tCell Is Nothing Then Exit Sub
Dim langCol As Long
Select Case tCell.Value
Case "English": langCol = 2
Case "French": langCol = 3
' easily add more
Case Else: Exit Sub
End Select
Application.EnableEvents = False ' prevent retriggering the event
' Sheets("Data") could be replaced with 'Me' and use a variable for others.
' To improve readability you could do:
Dim tws As Worksheet: Set tws = Me.Parent.Worksheets("T")
Cells(1, 1).Value = tws.Cells(5, langCol).Value
Cells(2, 1).Value = tws.Cells(6, langCol).Value
'....many more cell swaps here 100 total
SafeExit:
If Not Application.EnableEvents Then Application.EnableEvents = True
Exit Sub
ClearError:
Debug.Print "Run-time error '" & Err.Number & "': " & Err.Description
Resume SafeExit
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.