繁体   English   中英

单元格+其他单元格数据的前三个值VBA Excel

[英]First three values from cell + other cell data VBA Excel

我有两个表,我需要使用VBA将数据从一个表获取到另一个表。 我有一个导入数据的代码,并将它们放在我需要的列范围内,但是我仍然坚持格式化它们:

  1. 我需要检查日期列单元格是否为空,是否为空,而不是从其他单元格放入日期

    If IsEmpty(oldtable.Range("L3", "L10").Value) Then

    newtable.Range("J3", "J10").Value = newtable.Rang("E3", "E10").Value

    Else newtable.Range("J3", "J10").Value = oldtable.Rang("L3", "E10").Value

    End if

  2. 需要从数字+来自相同范围的单元格的值中获得前3个字符串

    newtable.Range("O3", "O10").Value = Mid(newtable.Range("M3", "10").Value,1,3)&newtable.Range("N3", "N10").Value

代码对我不起作用。 谢谢你的支持!

完整代码:

Dim filter As String
Dim caption As String
Dim file As String
Dim oldtable As Workbook
Dim newtable As Workbook

Range("A3:R10").Select
Selection.ClearContents

Set newtable = Application.ActiveWorkbook

filter = "Text files (C:\Excel\file.xlsx),C:\Excel\file.xlsx"
caption = "Please Select an input file "
GREMPG1 = Application.GetOpenFilename(filter, , caption)

oldtable = Application.Workbooks.Open(GREMPG1)

Dim wsheet_new1 As Worksheet
Set wsheet_new1 = newtable.Worksheets(1)
Set wsheet_new2 = newtable.Worksheets(2)

Dim wsheet_old As Worksheet
Set wsheet_old = oldtable.Worksheets(1)

'This is OK
wsheet_new1.Range("C3", "C11").Value = wsheet_new1.Range("C2").Value 

'This is OK
wsheet_new1.Range("D3", "D11").Value = Application.WorksheetFunction.VLookup(wsheet_old.Range("E2", "E10"), wsheet_new2.Range("A1:B16").Value, 2, False)

'Empty values stay empty
    If IsEmpty(wsheet_old.Range("L3", "L11").Value) Then
        wsheet_new1.Range("J3", "J11").Value = wsheet_new1.Range("E3", "E11").Value
    Else
        wsheet_new1.Range("J3", "J11").Value = wsheet_old.Range("L2", "L10").Value
    End If

GREMPG1_wb.Close


End Sub

IsEmpty函数的帮助指出:

如果变量未初始化或显式设置为Empty,则IsEmpty返回True。 否则,返回False。如果expression包含多个变量,则始终返回False。 IsEmpty仅返回有意义的变体信息。

因为您要传递多个单元格("L3", "L11")所以IsEmpty函数始终返回False。 最简单的答案是编写一个接受Range并测试每个单元格并返回True / False的函数。 功能如下:

Private Function RangeIsEmpty(ByRef theRange As Range) As Boolean

Dim cell As Range
Dim result As Boolean

    result = True
    For Each cell In theRange.Cells
        If Not IsEmpty(cell) Then
            result = False
            Exit For
        End If
    Next cell

    RangeIsEmpty = result

End Function

将函数复制到与代码相同的模块中。 然后更改此行:

If IsEmpty(wsheet_old.Range("L3", "L11").Value) Then

至:

If RangeIsEmpty(wsheet_old.Range("L3", "L11").Value) Then

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM