阅读在VBA中操作和编写数据

时间:2015-07-24 18:54:28

标签: excel vba excel-vba

如果我有一列值,如何将值读入VBA中的变量,对其执行某些操作然后将其写入下一列?看起来很简单,但我还没有找到一个简单的指南。

例如:

A栏= 1,4,5,7

没有将公式写入B列

Dim A,B

A = a栏

B = log(A)

将B的值写入下一列。

谢谢!

3 个答案:

答案 0 :(得分:1)

如果你想循环整张表,你可以这样做。

Dim lRow as long
Dim strA as string
Dim strB as string

Dim ws As Excel.Worksheet
Set ws = ActiveWorkbook.Sheets("Sheet1")

lRow = 1
Do While lRow <= ws.UsedRange.Rows.count

   'Read the data from columnA
   strA = ws.Range("A" & lRow).Value

   'do something with the value you got from A
   strB  = strA & "some other text"
   strB = log(strA)

   'Write it to C
   ws.Range("C" & lRow).Value = strB

   lRow = lRow + 1
   ws.Range("A" & lRow).Activate
Loop

或者,如果您只是想要某个预定义的行,那么就会更加难以编码。

'Read the data from columnA
strA = ws.Range("A6").Value

'do something with the value you got from A
strB  = strA & "some other text"
strB = log(strA)

'Write it to C
ws.Range("C6").Value = strB

答案 1 :(得分:0)

试试这个宏:

Sub test()
    Dim cel As Range, rng As Range
    Dim logCel As Double
    Dim lastRow As Integer

lastRow = Cells(1048576, 1).End(xlUp).Row
Set rng = Range(Cells(1, 1), Cells(lastRow, 1)) 'Create a range to search

For Each cel In rng
    If Not IsEmpty(cel) Then 'If the cell has a value in it
        logCel = Log(cel) 'add the LOG of the value to a variable
        cel.Offset(0, 1).Value = logCel 'In the cell to the right of the cell, put the log
    End If
Next cel

End Sub

要了解有关设置单元格值等的信息,我强烈建议您使用宏录制器,然后在完成后查看宏。启动录像机,然后在单元格中输入一个值,然后在下一个单元格中输入该日志,您将了解VBA的工作原理。

答案 2 :(得分:0)

不是逐个循环遍历,而是使用LOG公式直接写入工作表(不需要数组,因为操作可以直接用于插入公式):

Sub LikeThis()
Dim rng1 As Range
`work on A1:A20 and write to B1:B20
Set rng1 = [a1:a20]
rng1.Offset(0, 1).FormulaR1C1 = "=IF(RC[-1]>0,LOG(RC[-1]),""not valid"")"
End Sub