我有几张相关的表格,但我有2张活动表格。当我在"表2"我需要知道单元格(" C14")何时通过我猜测的IF语句变为活动状态。一旦它变为活动状态,我就需要知道表1中单元格中的字符串(" B2")="战斗机"那么我想在这里插入关于战斗机的一些措辞"在第2页的单元格中(" C14")如果它不是"战斗机"那么它是" Mage"?如果是这样,那么在这里插入"关于法师的一些措辞"。
这是一个简短的例子。
如果工作表2上的单元格C14是活动的,那么 检查Sheet1上的单元格B2。如果文字="战斗机"?然后 插入"你是勇敢的并且使用剑"进入细胞C14 Sheet2 如果它不等于战斗机那么它是"法师"?然后 插入"你施放法术"在单元格C14 sheet2中 等。
我需要知道如何在VBA中编写代码。我花了好几个小时搜索和尝试各种代码,但似乎无法做到正确。提前谢谢你的帮助。
答案 0 :(得分:0)
尝试这样的事情:
'The way you check which cell is active is by using an
'Event like this one. This goes into the Sheet2 code module
'which you can get to by right clicking on the sheet's tab and
'selecting View Code.
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim rng_Source As Excel.Range
Dim rng_Target As Excel.Range
On Error GoTo ErrorHandler
'Setting the cells that you're interested in as
'ranges will help minimise typo errors.
Set rng_Target = ThisWorkbook.Sheets("Sheet2").Range("C14")
Set rng_Source = ThisWorkbook.Sheets("Sheet1").Range("B2")
'Target is a range that specifies the new
'selection. Check its address against rng_Target
'which we defined above.
If Target.Address <> rng_Target.Address Then
Exit Sub
End If
'If you don't want case sensitivity, convert to upper case.
If UCase(rng_Source.Value) = "FIGHTER" Then
rng_Target.Value = "some wording regarding the fighter here"
ElseIf UCase(rng_Source.Value) = "MAGE" Then
rng_Target.Value = "You cast spells"
'You get the idea.
End If
ExitPoint:
On Error Resume Next
'Clean up
Set rng_Source = Nothing
Set rng_Target = Nothing
On Error GoTo 0
Exit Sub
ErrorHandler:
MsgBox "Error " & Err.Number & vbCrLf _
& Err.Description
Resume ExitPoint
End Sub
我同意这些评论,你应该总是发布你已经尝试过的代码(你后来做了),但这是一个相对微不足道的代码,这只是将它清除掉,可能是在将来对别人有用。
答案 1 :(得分:0)
试试这个;)
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
On Error GoTo errH
Dim rng1 As Range
Set rng1 = ThisWorkbook.Worksheets(1).Range("B2")
If Not Intersect(Target, Me.Range("C14")) Is Nothing Then
Application.EnableEvents = False
If rng1.Value2 = "Mage" Then
Target.Value = "OMG This is MAGE!!! Run run run away!!!"
ElseIf rng1.Value2 = "Fighter" Then
Target.Value = "Fighter? :/ Was hoping for something better"
MsgBox "Fighter? :/ Was hoping for something better"
rng1.Value2 = "Mage"
Target.Value = "Mage. Now This is better ;)"
Else
Target.Value = "No, we haven't discussed it."
End If
Application.EnableEvents = True
End If
Exit Sub
errH:
MsgBox ("Error number: " & Err.Number & "Description: " & Err.Description)
Application.EnableEvents = True
End Sub