在VBA中读取操作和写入数据

如果我有一列值,如何读取VBA中的variables值,对其执行一些操作,然后将其写入下一列? 似乎头脑麻木,但我一直没能find一个简单的指南。

例如:

列A = 1,4,5,7

无需将公式写入B列

昏暗的A,B

A =栏a

B = log(A)

将B的值写入下一列。

谢谢!

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

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 

试试这个macros:

 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 

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

您可以使用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