
VBA编程中,变量赋值给单元格是常见的操作。例如:
Sub aa()
Dim x As String
x = "资产"
Cells(m, n) = x 'm代表行标,n代表列标,根据不同情况可以用数字代替。
end sub
如果不是给当前工作表赋值,可以使用以下格式:
Sheets("Sheet1").Range("B2") = 100 '把100赋值给sheet1工作表中的B2单元格
也可以给某一个区域赋值:
Range("A1:A100").Select
Selection = 100
Selection就可以标识当前选中的单元格,上面2句代码是将当前选中的单元格写入100。
程序可以改为下面代码:
Sub CommandButton1_Click()
Application.ScreenUpdating = False
Dim i As Integer
Dim j As Integer
Dim zcbh As Variant
Dim ytzj As Variant
Dim yjzj As Variant
Dim sh As Worksheet
For i = 3 To 10
zcbh = Sheets("8").Cells(i, 3)
Sheets("6").Activate
Sheets("6").Columns(2).Find(what:=zcbh).Activate
ActiveCell.Offset(0, 5).Select
ytzj = ActiveCell.Value
Sheets("8").Activate
Sheets("8").Cells(i, 8).Value = ytzj
Next i
MsgBox "程序运行完毕"
Application.ScreenUpdating = True
End Sub
修改为以下代码:
Sub CommandButton1_Click()
Application.ScreenUpdating = False
Dim i As Integer
Dim j As Integer
Dim zcbh As Variant
Dim ytzj As Variant
Dim yjzj As Variant
Dim sh6 As Worksheet
Dim sh8 As Worksheet
Set sh6 = ThisWorkbook.Sheets("sheet6")
Set sh8 = ThisWorkbook.Sheets("sheet8")
For i = 3 To 10
zcbh = sh8.Cells(i, 3)
sh6.Activate
sh6.Columns(2).Find(what:=zcbh).Activate
ActiveCell.Offset(0, 5).Select
ytzj = ActiveCell.Value
sh8.Cells(i, 8) = ytzj
Next i
MsgBox "程序运行完毕"
Application.ScreenUpdating = True
End Sub