簡體   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