[英]VBScript to multiply column values in excel and paste the results in different column
I am trying to use a VBScript to perform the excel function below 我正在尝试使用VBScript执行以下excel函数
B=A:A * 0.5 B = A:A * 0.5
That is multiply all the value in column A by 0.5 and paste those values into column B. I would like to do this outside of Excel. 那就是将A列中的所有值乘以0.5,然后将这些值粘贴到B列中。我想在Excel之外执行此操作。
With the help of @GarysStudent 's answer, I was able to get the multiplication and pasting within the original column, Column A to work. 借助@GarysStudent的答案,我能够在原始列A内进行乘法和粘贴。 Ideally I would like to paste the multiplied results in Column B.
理想情况下,我想将相乘的结果粘贴到B列中。
Below is the VBScript code for multiplying and pasting values within the same column 以下是用于在同一列中相乘和粘贴值的VBScript代码
Imports Excel = Mircosoft.Office.Interop.Excel
Public Class Form1
Dim objExcel, objXLWorkbook, objXLWS, RNGE, LNG, lRow, nRow
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
objExcel = CreateObject("Excel.Application")
objXLWorkbook = objExcel.Workbooks.Open("C:\filename.xlsx")
objXLWS = objXLWorkbook.Worksheets(1)
objExcel.Visible = True
'Adding Helper Cell to hold the multiplication value
objXLWS.Range("Z100") = 0.5
With objXLWS
LNG = .Cells(.Rows.Count, "A").End(Excel.XlDirection.xlUp).Row
RNGE = .Range("A2:A" & LNG)
.Range("Z100").Copy()
RNGE.PasteSpecial(Excel.XLPasteType.xlPasteAll, Excel.XlPasteSpecialOperation.xlPasteSpecialOperationMultiply)
End With
End Sub
End Class
You can use a for loop if you know the size of your data, or a do while if you don't: 如果您知道数据的大小,则可以使用for循环;如果不知道,则可以使用do循环:
Dim x As Double
x = Range(Cells(1, 1), Cells(1, 1).End(xlDown)).Count
For i = 1 To x
Cells(i, 2).Value = Cells(i, 1).Value * 0.5
Next
This works but it is a little slow, it counts how many entries you have and then loops through. 这可行,但是有点慢,它会计算您有多少条目,然后循环遍历。 i would recommend using a spreadsheet function for speed though.
我建议尽管使用电子表格功能以提高速度。
This example uses cell Z100 as a "helper" cell: 本示例使用单元格Z100作为“帮助”单元格:
Sub DEMO()
Dim r As Range, N As Long
Range("Z100").Value = 0.5
N = Cells(Rows.Count, "A").End(xlUp).Row
Set r = Range("A1:A" & N)
Range("Z100").Copy
r.PasteSpecial Paste:=xlPasteAll, Operation:=xlMultiply
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.