使用左function

我试图创build一个简单的macros,复制列中的每个单元格中的两个第一个数字,并将其打印在不同的列中。 这是一个超过1个工作表的Excel文档。 我已经尝试了一段时间来编写代码,但是没有以前的经验,我很难搞清楚该怎么做。 我知道“left()”函数能够做到这一点,但我不知道如何定义从哪个列中绘制数据,以及将要打印哪一列。 任何帮助将不胜感激。

没有以前写VBA代码的经验,我会推荐你​​坚持公式的做法。 老实说,即使你熟悉VBA,你仍然可以select使用公式。

一个公式被放入你想要复制的值的实际单元格中。

=LEFT(sourceCell, #of characters you want) 

这是看起来如何:

 =LEFT(Sheet1!A1, 2) 

把它想成“这个单元格应该等于单元格OO中的前n个字符,从左边开始”。

一旦你完成了你的公式,如果你不需要绑定到源(如果源单元格改变了,左单元格也是如此),你可以突出显示单元格,Ctrl + C来复制,然后右键单击并selectselect性粘贴 。 然后selectVALUE ,然后点击确定,现在单元格将被硬编码,显示的值就像您自己input的一样。

掌握使用公式后,下一步就是VBA。 如果你不习惯使用= LEFT,那么跳进VBA和编写范围代码等等,不要混淆你自己。 一步一个脚印,在你知道之前你会成为职业球员。 🙂

下面是一个快速入门示例:

 Public Sub LeftSub() Dim SourceRange As Range, DestinationRange As Range, i As Integer 'Define our source range as A1:A10 of Sheet1 Set SourceRange = Sheet1.Range("A1:A10") 'Define our target range where we will print. 'Note that this is expected to be of same shape as source Set DestinationRange = Sheet1.Range("B1:B10") 'Iterate through each source cell and print left 2 bits in target cell For i = 1 To SourceRange.Count DestinationRange(i, 1).Value = Left(SourceRange(i, 1).Value, 2) Next i End Sub 

怎么样

 Sub foo() Dim cell As Range Dim sourceRange As Range '//define the source column - looks for contiguous downward data from A1; Set sourceRange = Range(Sheets("Sheet1").Range("A1"), Selection.End(xlDown)) '//iterate each cell For Each cell In sourceRange If IsEmpty(cell.Value) Then Exit For '//example to place the value in corresponding row of column B in sheet 2 Sheets("Sheet2").Range("B" & cell.Row).Value = Left$(cell.Value,2) Next End Sub 

或者一个等价的公式(在目标单元格中​​)

 =LEFT(Sheet1!A1,2)