从其他模块传递变量并将其放入格式中

时间:2016-12-26 10:29:03

标签: excel vba excel-vba

我有一个问题,因为我不熟悉如何编码格式,因为我传递的变量是来自其他模块的数字。我已经发布了我的代码sub record(这是我的excel vba中的模块9)。这个子模块是我需要将字段修改为某种格式的地方,我需要从其他模块传递的值。我从模块2传递一个变量,它将返回一个数字,因为我已将其声明为Public myVal As String,因为我需要此Myval值并以格式将其插入此字段3。

字段3的值是000000000209644(数字的15位数)我需要修改为这样的020161201209644

  1. 0201612 = 0 + YYYYMM

  2. 01 =来自其他模块2的myval值

  3. 209644 =此文件中的当前数字数据。

  4. 以下是我的示例代码,以显示我在做什么

    Sub record()
    
    Dim myfile, mysfile, myxfile As String
    
    myfile = ThisWorkbook.Path + "\PaymentFile02.xlsx"
    Open DatFile1Name For Output As #1
    
    Application.Workbooks.Open FileName:=myfile
    vRow = 2
    While Cells(vRow, 1).Value <> ""
        Field1 = Cells(vRow, 1).Value
        Field2 = Cells(vRow, 2).Value
        Field3 = Cells(vRow, 3).Value ' this is the variable where i need to do formatting
    
        Dim Str As String
        str =""
        str = field1 & "|" & field2 & "|" & Field3 & "|"
        Print #1, str
        vRow = vRow + 1 ' this is incremental as there are a lot of rows
    Wend
    Close #1
    
    ActiveWorkbook.Close
    MsgBox ("File PaymentFile02.TXT created")
    
    End Sub
    

    字段1,字段2和字段3的示例数据:

    00|HELLO|000000000209644|
    

2 个答案:

答案 0 :(得分:1)

使用格式构建你的str。

格式化函数(Visual Basic for Applications) https://msdn.microsoft.com/en-us/library/office/gg251755.aspx

Str =“0”&amp;格式(field1,“YYYYMM”)&amp;等

Dunno如果你的3 field3应该是field1,field2和field3 ......

答案 1 :(得分:1)

下面的代码会在您的帖子中按照您的要求进行Str合并。

注意:考虑一下,它需要右边的前6位数字(在15位数字中) - 这是下面代码中的常量格式(可以修改为适合其他场景)。

Sub record(myVal As String)

Dim myfile As String, mysfile As String, myxfile As String

myfile = ThisWorkbook.Path & "\PaymentFile02.xlsx"

Open DatFile1Name For Output As #1
Application.Workbooks.Open (myfile)

vRow = 2
While Cells(vRow, 1).Value <> ""
    field1 = Cells(vRow, 1).Value
    field2 = Cells(vRow, 2).Value

    ' this assumes your value in Column C will allways take 6 digits from the right
    Field3 = 0 & Format(Date, "YYYYMM") & myVal & Format(Cells(vRow, 3).Value, "000000") ' This is the variable where i need to do formatting

    Dim Str As String

    Str = ""
    Str = field1 & "|" & field2 & "|" & Field3 & "|"

    Debug.Print Str

    Print #1, Str
    vRow = vRow + 1 ' This is incremental as there are a lot of rows
Wend
Close #1

ActiveWorkbook.Close
MsgBox ("File PaymentFile02.TXT created")

End Sub