简体   繁体   English

如何从正则表达式生成随机文本以填充Excel单元格

[英]How to generate random text from regex to fill an excel cell

I'm creating a large amount of Excel test files with different values in many columns. 我正在创建大量的Excel测试文件,在许多列中具有不同的值。

(Windows 7 - 64 bits system (if relevant)). (Windows 7-64位系统(如果相关))。

These files are going to be imported into a database later using other unknown tool, so I just have to prepare only these files filled with valid data. 这些文件以后将使用其他未知工具导入数据库,因此我只需要准备这些填充有有效数据的文件。

Each file has different columns, so different ranges of valid characters are necessary per column. 每个文件都有不同的列,因此每列需要不同范围的有效字符。

What would I want to do? 我想怎么办?

Use a Formula witch receive a regex and generate/and fill the cell with a random string based on that regex and if possible specify how many characters the string should be. 使用公式巫婆接收一个正则表达式,并根据该正则表达式生成/填充一个随机字符串,并在可能的情况下指定该字符串应包含多少个字符。

Something like this site does: https://www.browserling.com/tools/text-from-regex 像本网站一样: https//www.browserling.com/tools/text-from-regex

For example: For the next columns, I would like to populate cells with random text as follows: 例如:对于接下来的列,我想用随机文本填充单元格,如下所示:

> 
> -------------------------------------------------------------------
> | Name      | Email          | Date  | URL               | Price  |
> -------------------------------------------------------------------
> | AHygsyub  | xyz@uygsh.hyu  | 1956  | http://iadif.jyf  | 245.75 |
> -------------------------------------------------------------------

Using something like this in the Formula bar: 在公式栏中使用如下所示的内容:

> =fillCellWith('([a-z]{3,10} ){1,10}')              //For Name column
> =fillCellWith('\d{4}')                             //For Date column
> =fillCellWith(RegexPattern)                        //Etc etc

Can someone guide me in the creation of a VBA Function to accomplish this purpose? 有人可以指导我创建VBA功能来实现此目的吗?

I don't have any experience in VB programming, but I can imagine something like: 我没有任何VB编程经验,但是我可以想象像这样的东西:

Public Function fillCellWith(MyRegex As String) As String
Dim regEx As New RegExp
Dim Rand As String

'Analize the pattern and create random string satisfying the pattern needs to be valid
'Merge all parts and return as a result in Rand


End Function

Got it! 得到它了! Using Java language + VBA Excel and based on these links: 使用Java语言+ VBA Excel并基于以下链接:

Microsoft Excel Macro to run Java program Microsoft Excel Macro运行Java程序

https://www.ozgrid.com/forum/forum/help-forums/excel-general/142069-calling-and-executing-a-java-program-from-excel-vba-macro https://www.ozgrid.com/forum/forum/help-forums/excel-general/142069-calling-and-executing-a-java-program-from-excel-vba-macro

Here i found lots of libraries that already generate values based on a regex. 在这里,我发现了很多已经基于正则表达式生成值的库。

I chose this to test. 我选择进行测试。

Why? 为什么? , I tested with Javascript libraries, but i found it very complicated to use along with VBA, Phyton libraries less complicated, but when i saw an example with Java was desicive. ,我使用Javascript库进行了测试,但是发现将它与VBA一起使用非常复杂,Phyton库则不那么复杂,但是当我看到Java的示例很吸引人时。

What i did was: 我所做的是:

1 - Download generex.jar version 1.0.2 with dependencies from here 1-从此处下载generex.jar 1.0.2版本及其相关性

2 - Create a Java Project with a Main class, in my case RegexToValue with the following code: 2-使用主类创建一个Java项目,在我的示例中为RegexToValue ,其代码如下:

import com.mifmif.common.regex.Generex;

//args[0] receive regex to init Generex Object
public class RegexToValue {
    public static Generex generex;
    public static int attempts = 0;

    public static void main(String[] args) {
        if (args.length > 0) {
            generex = new Generex(args[0]);
        } else {
            generex = new Generex("[0-3]([a-c]|[e-g]{1,2})"); //default init
        }
        generateValue();
    }

    public static void generateValue() {
        try {
            System.out.print(generex.random());
        } catch(Error e) {
            if (attempts <= 3) {
                attempts++;
                generateValue();
            } else {
                System.out.print("Error");
            }
        }
    }
}

3 - Import the two .jars downloaded from step 1 into the project (Libraries -> Add JAR file) 3-将从第1步下载的两个.jar导入到项目中(库->添加JAR文件)

4 - Generate JAR file of the project with imported dependencies from step 3, all together 4-一起生成具有步骤3中导入的依赖项的项目的JAR文件

5 - I put the generated JAR and the Lib folder into C:\\Generex\\ for simplicity 5-为了简单起见,我将生成的JAR和Lib文件夹放入C:\\ Generex \\

6 - Create an Excel file enabled for Macros 6-创建为宏启用的Excel文件

7 - Create a Module (Alt + F11) -> Menu Insert -> Module with the following code: 7-使用以下代码创建模块(Alt + F11)->菜单插入->模块

#If VBA7 Then
    '64 Bits
    Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As LongPtr)
#Else
    '32 Bits
    Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
#End If

Public Function fillCellWith(regxPattern As String)
    Dim prog As Object

    '// pass the program name to java on command line, and pass any arguments after.
    Set prog = CreateObject("WScript.Shell").exec("javaw -jar ""C:\Generex\RegexToValue.jar"" " & regxPattern)
    While prog.Status = 0
        Sleep 1000 '// put thread to sleep for 1 sec.
    Wend
    fillCellWith = prog.StdOut.ReadAll
End Function

8 - Use a formula like this in a cell: 8-在单元格中使用如下公式:

=fillCellWith("(blue|red|yellow|green)\.(oak|cedar|willow)\@(yahoo\.co\.uk|google\.com|example\.org)")

9 - See results =) 9-查看结果=)

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

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