我的第一个问题是细胞(i,4)命令做了什么,一直到细胞(i,7)。
Option Explicit
Sub batch1()
Sheets("Batch").Activate
Range("A1").Activate
Dim name, office As String
Dim q1, q2, q3, q4 As Double
Dim i As Integer
i = 2
Do Until IsEmpty(ActiveCell)
DoEvents
name = ActiveCell.Offset(0, 1) & " " & ActiveCell.Offset(1, 1)
office = ActiveCell.Offset(2, 1)
q1 = ActiveCell.Offset(3, 1)
q2 = ActiveCell.Offset(4, 1)
q3 = ActiveCell.Offset(5, 1)
q4 = ActiveCell.Offset(6, 1)
Cells(i, 4) = name
Cells(i, 5) = office
Cells(i, 6) = WorksheetFunction.Sum(q1, q2, q3, q4)
Cells(i, 7) = WorksheetFunction.Average(q1, q2, q3, q4)
i = i + 1
ActiveCell.End(xlDown).Activate
ActiveCell.End(xlDown).Activate
Loop
Range("a1").Activate
End Sub
我的下一个问题是为什么我们必须.activate这个工作表和第一个单元格,我们不能只是开始吐出代码而不激活它,或者是否有一些特定的代码使我们必须激活它?
Option Explicit
Sub batchPractice()
Dim name, place, weapon As String
Dim iCount As Integer
Dim candlestick, dagger, leadpipe, revolver, rope, wrench As Integer
iCount = 1
Sheets("BatchPractice").Activate
Range("a1").Activate
Do Until IsEmpty(ActiveCell)
DoEvents
name = ActiveCell
place = ActiveCell.Offset(1, 0)
weapon = ActiveCell.Offset(2, 0)
Cells(iCount, 3) = name & " in the " & place & " with the " & weapon
iCount = iCount + 1
If weapon = "Candlestick" Then
candlestick = candlestick + 1
ElseIf weapon = "Dagger" Then
dagger = dagger + 1
ElseIf weapon = "Dagger" Then
dagger = dagger + 1
ElseIf weapon = "Lead Pipe" Then
leadpipe = leadpipe + 1
ElseIf weapon = "Revolver" Then
revolver = revolver + 1
ElseIf weapon = "Rope" Then
rope = rope + 1
ElseIf weapon = "Wrench" Then
wrench = wrench + 1
Else
MsgBox ("Unknown weapon: " & weapon)
End If
ActiveCell.End(xlDown).Activate
ActiveCell.End(xlDown).Activate
Loop
Range("E2") = candlestick
Range("E3") = dagger
Range("E4") = leadpipe
Range("E5") = revolver
Range("E6") = rope
Range("E7") = wrench
End Sub
答案 0 :(得分:3)
1)Cells
做什么?
Cells属性从您指定的单元格获取/设置数据。在你的例子中:
Cells(i, 4) = name
,您试图将该名称放入我们正在循环(i)和第4列的行中。
2)为什么我们必须.activate
此工作表和第一个单元格,我们是否只是在不激活它的情况下开始吐出代码?
目前,此脚本正在从" Batch"中提取数据。工作表,因此它激活只关注该特定工作表。通常,如果您没有指定工作表,VBA将使用上次激活的工作表。
该单元格已激活,因为它随后开始使用ActiveCell.Offset(2, 1)
之类的特定单元格,因此从A1向下2行,跨越1列。使用Range("C2").Value
或Cells(3, 2).Value
可以实现同样的效果,因为它实际上似乎没有改变价值。
我建议您上网一些课程,我将YouTube用作VBA快速速成课程。我觉得这是最简单的语言。
答案 1 :(得分:1)
如果变量正确变暗,如果将变量留空,则变为变量。
如果您正确启动代码,则无需激活或选择任何内容。
以下是您的第一个代码示例。您可以从工作簿中的任何位置运行它。
Sub Button1_Click()
Dim sh As Worksheet
Dim Rws As Long, Rng As Range, c As Range
Dim name As String, office As String, i
Dim q1 As Double, q2 As Double, q3 As Double, q4 As Double
Set sh = Sheets("Batch")
With sh
Rws = .Cells(Rows.Count, "A").End(xlUp).Row
Set Rng = Range(.Cells(1, 1), .Cells(Rws, 1))
For Each c In Rng.Cells
name = c.Offset(0, 1) & " " & c.Offset(1, 1)
office = c.Offset(2, 1)
i = c.Row
q1 = c.Offset(3, 1)
q2 = c.Offset(4, 1)
q3 = c.Offset(5, 1)
q4 = c.Offset(6, 1)
.Cells(i, 4) = name
.Cells(i, 5) = office
.Cells(i, 6) = WorksheetFunction.Sum(q1, q2, q3, q4)
.Cells(i, 7) = WorksheetFunction.Average(q1, q2, q3, q4)
Next c
End With
End Sub