来自单元格的前三个值 + 其他单元格数据 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 函数的帮助说明:

IsEmpty returns True if the variable is uninitialized, or is explicitly set to Empty; otherwise, it returns False.False is always returned if expression contains more than one variable. IsEmpty only returns meaningful information for variants.

因为您要传递多个单元格 ("L3", "L11"),所以 IsEmpty 函数总是 returns False。最简单的答案是编写一个接受 Range 并测试每个单元格和 returns 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