2016-12-26 63 views
0

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

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

  1. 0201612 = 0 + YYYYMM

  2. 01 =设为myVal从其它模块2值

  3. 209644 =是此文件中的当前编号数据。

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

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| 
+0

看看下面为你的作品我的答案代码如预期 –

回答

1

下面的代码是Str合并就像你想在你的文章。

注意:考虑到它需要右前15位数字中的前6位数 - 这是下面代码中的常数格式(可以修改为适合其他情况)。

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 
+0

是的,这正是我需要的,非常感谢你 –

+0

不客气:) –

1

构建使用格式的STR 。

格式化功能(Visual Basic应用程序) https://msdn.microsoft.com/en-us/library/office/gg251755.aspx

海峡= “0” &格式(字段1, “YYYYMM”)&等

说不上来,如果你的3场3的应该是字段1,字段2和field3 ...

+0

您好,我已经添加了样本数据为我场1场2场和3 –

+0

是的,它应该是1场,2场和字段3,抱歉的错误 –

+0

但我怎么去通过我的变量从其他模块,Myval从其他模块 –

相关问题